/**
 * Server management commands.
 */

import { Command } from 'commander';
import { getServerManager } from '../server-manager.js';
import { EmdashClient } from '../client.js';
import { style } from '../design.js';

export const serverCommand = new Command('server')
  .description('Server management commands')
  .addCommand(
    new Command('start')
      .description('Start the emdash server')
      .action(async () => {
        const manager = getServerManager();

        try {
          const url = await manager.ensureServer();
          console.log(style.success(`Server running at ${url}`));
        } catch (error) {
          console.error(style.error('Failed to start server:'), (error as Error).message);
          process.exit(1);
        }
      })
  )
  .addCommand(
    new Command('status')
      .description('Check server status')
      .action(async () => {
        const manager = getServerManager();

        try {
          const url = await manager.getServerUrl();
          const client = new EmdashClient(url);
          const health = await client.health();

          console.log(style.success('Server is running'));
          console.log(`  URL: ${url}`);
          console.log(`  Status: ${health.status}`);
          if (health.version) {
            console.log(`  Version: ${health.version}`);
          }
        } catch (error) {
          console.log(style.muted('Server is not running'));
        }
      })
  )
  .addCommand(
    new Command('stop')
      .description('Stop the emdash server')
      .action(async () => {
        const manager = getServerManager();
        manager.shutdown();
        console.log(style.success('Server stopped'));
      })
  )
  .addCommand(
    new Command('killall')
      .description('Kill all running emdash servers')
      .action(async () => {
        // Import node modules
        const { execSync } = await import('node:child_process');

        try {
          // Kill all Python emdash_core.server processes
          execSync("pkill -f 'python.*emdash_core.server' || true", { stdio: 'pipe' });
          console.log(style.success('All emdash servers killed'));
        } catch (error) {
          console.error(style.error('Failed to kill servers:'), (error as Error).message);
        }
      })
  );
