/**
 * Swarm commands.
 */

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

export const swarmCommand = new Command('swarm')
  .description('Multi-agent swarm commands')
  .addCommand(
    new Command('run')
      .description('Run a multi-agent swarm')
      .argument('<tasks...>', 'Tasks for the swarm to execute')
      .option('-m, --model <model>', 'Model to use')
      .option('--auto-merge', 'Automatically merge results')
      .action(async (tasks: string[], options: { model?: string; autoMerge?: boolean }) => {
        const manager = getServerManager();
        const url = await manager.ensureServer();
        const client = new EmdashClient(url);
        const renderer = new SSERenderer(true);

        try {
          console.log(`Starting swarm with ${tasks.length} tasks...`);
          console.log();

          const stream = client.swarmRunStream(
            tasks,
            options.model,
            options.autoMerge ?? false
          );

          await renderer.renderStream(stream);
        } catch (error) {
          console.error(style.error('Swarm execution failed:'), (error as Error).message);
          process.exit(1);
        }
      })
  )
  .addCommand(
    new Command('status')
      .description('Get swarm execution status')
      .action(async () => {
        const manager = getServerManager();
        const url = await manager.ensureServer();
        const client = new EmdashClient(url);

        try {
          const status = await client.swarmStatus();
          console.log('Swarm Status:');
          console.log(JSON.stringify(status, null, 2));
        } catch (error) {
          console.error(style.error('Failed to get status:'), (error as Error).message);
          process.exit(1);
        }
      })
  );
