#!/usr/bin/env bun

import {$} from "bun";

const SERVICES = {
  ap: "phone-ap",
  web: "phone-web",
};

const commands = {
  status: "Show status of all services",
  logs: "Show recent logs from all services (last 50 lines)",
  tail: "Tail logs from all services in real-time",
  restart: "Restart all services",
  stop: "Stop all services",
  start: "Start all services",
  "ap-status": "Show status of AP service",
  "ap-logs": "Show recent logs from AP service (last 50 lines)",
  "ap-tail": "Tail logs from AP service in real-time",
  "ap-restart": "Restart AP service",
  "ap-stop": "Stop AP service",
  "ap-start": "Start AP service",
  "web-status": "Show status of web service",
  "web-logs": "Show recent logs from web service (last 50 lines)",
  "web-tail": "Tail logs from web service in real-time",
  "web-restart": "Restart web service",
  "web-stop": "Stop web service",
  "web-start": "Start web service",
  help: "Show this help message",
};

const command = process.argv[2];

if (!command || command === "help") {
  console.log(`
Yellow Phone CLI - Service Management Tool

Usage: bun cli <command>

All Services:
  status         Show status of all services
  logs           Show recent logs from all services (last 50 lines)
  tail           Tail logs from all services in real-time
  restart        Restart all services
  stop           Stop all services
  start          Start all services

AP Service (phone-ap):
  ap-status      Show AP status
  ap-logs        Show AP logs (last 50 lines)
  ap-tail        Tail AP logs in real-time
  ap-restart     Restart AP service
  ap-stop        Stop AP service
  ap-start       Start AP service

Web Service (phone-web):
  web-status     Show web status
  web-logs       Show web logs (last 50 lines)
  web-tail       Tail web logs in real-time
  web-restart    Restart web service
  web-stop       Stop web service
  web-start      Start web service

Examples:
  bun cli status
  bun cli ap-logs
  bun cli web-tail
  sudo bun cli ap-restart
`);
  process.exit(0);
}

if (!Object.keys(commands).includes(command)) {
  console.error(`❌ Unknown command: ${command}`);
  console.log(`Run 'bun cli.ts help' to see available commands`);
  process.exit(1);
}

console.log(`\n🔧 Yellow Phone CLI - ${command}\n`);

// Parse service-specific commands
const match = command.match(/^(ap|web)-(.+)$/);
if (match) {
  const [, prefix, action] = match;
  const service = SERVICES[prefix as keyof typeof SERVICES];

  switch (action) {
    case "status":
      console.log(`━━━ ${service}.service ━━━`);
      await $`systemctl status ${service}.service --no-pager -l`.nothrow();
      break;

    case "logs":
      console.log(`📋 Recent logs (last 50 lines):\n`);
      await $`journalctl -u ${service}.service -n 50 --no-pager`.nothrow();
      break;

    case "tail":
      console.log(`📡 Tailing logs (Ctrl+C to stop)...\n`);
      await $`journalctl -u ${service}.service -f --no-pager`.nothrow();
      break;

    case "restart":
      console.log(`🔄 Restarting ${service}.service...\n`);
      await $`sudo systemctl restart ${service}.service`;
      console.log(`✓ ${service}.service restarted!`);
      break;

    case "stop":
      console.log(`🛑 Stopping ${service}.service...\n`);
      await $`sudo systemctl stop ${service}.service`;
      console.log(`✓ ${service}.service stopped!`);
      break;

    case "start":
      console.log(`▶️  Starting ${service}.service...\n`);
      await $`sudo systemctl start ${service}.service`;
      console.log(`✓ ${service}.service started!`);
      break;
  }
} else {
  // All-services commands
  const allServices = Object.values(SERVICES);

  switch (command) {
    case "status":
      for (const service of allServices) {
        console.log(`━━━ ${service}.service ━━━`);
        await $`systemctl status ${service}.service --no-pager -l`.nothrow();
        console.log("");
      }
      break;

    case "logs":
      console.log("📋 Recent logs (last 50 lines):\n");
      const serviceFlags = allServices.map(s => `-u ${s}.service`).join(" ");
      await $`journalctl ${serviceFlags} -n 50 --no-pager`.nothrow();
      break;

    case "tail":
      console.log("📡 Tailing logs (Ctrl+C to stop)...\n");
      const tailFlags = allServices.map(s => `-u ${s}.service`).join(" ");
      await $`journalctl ${tailFlags} -f --no-pager`.nothrow();
      break;

    case "restart":
      console.log("🔄 Restarting services...\n");
      for (const service of allServices) {
        console.log(`Restarting ${service}.service...`);
        await $`sudo systemctl restart ${service}.service`;
        console.log(`✓ ${service}.service restarted`);
      }
      console.log("\n✓ All services restarted!");
      break;

    case "stop":
      console.log("🛑 Stopping services...\n");
      for (const service of allServices) {
        console.log(`Stopping ${service}.service...`);
        await $`sudo systemctl stop ${service}.service`;
        console.log(`✓ ${service}.service stopped`);
      }
      console.log("\n✓ All services stopped!");
      break;

    case "start":
      console.log("▶️  Starting services...\n");
      for (const service of allServices) {
        console.log(`Starting ${service}.service...`);
        await $`sudo systemctl start ${service}.service`;
        console.log(`✓ ${service}.service started`);
      }
      console.log("\n✓ All services started!");
      break;
  }
}

console.log("");
