/**
 * Research command.
 */

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 researchCommand = new Command('research')
  .description('Deep research mode')
  .argument('<goal>', 'Research goal')
  .option('-m, --model <model>', 'Model to use')
  .option('--max-iterations <n>', 'Max iterations', '100')
  .option('--budget <n>', 'Research budget', '50')
  .action(async (goal: string, options: { model?: string; maxIterations: string; budget: string }) => {
    const manager = getServerManager();
    const url = await manager.ensureServer();
    const client = new EmdashClient(url);
    const renderer = new SSERenderer(true);

    try {
      console.log(`Starting research: ${goal}`);
      console.log();

      const stream = client.researchStream(
        goal,
        parseInt(options.maxIterations, 10),
        parseInt(options.budget, 10),
        options.model
      );

      await renderer.renderStream(stream);
    } catch (error) {
      console.error(style.error('Research failed:'), (error as Error).message);
      process.exit(1);
    }
  });
