/**
 * Project documentation 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 projectmdCommand = new Command('projectmd')
  .description('Generate PROJECT.md documentation')
  .option('-o, --output <file>', 'Output file', 'PROJECT.md')
  .option('--no-save', "Don't save to file")
  .option('-m, --model <model>', 'Model to use')
  .action(async (options: { output: string; save?: boolean; model?: string }) => {
    const manager = getServerManager();
    const url = await manager.ensureServer();
    const client = new EmdashClient(url);
    const renderer = new SSERenderer(true);

    try {
      console.log('Generating project documentation...');
      console.log();

      const stream = client.projectmdGenerateStream(
        options.output,
        options.save !== false,
        options.model
      );

      await renderer.renderStream(stream);

      if (options.save !== false) {
        console.log();
        console.log(style.success(`Documentation saved to ${options.output}`));
      }
    } catch (error) {
      console.error(style.error('Generation failed:'), (error as Error).message);
      process.exit(1);
    }
  });
