/**
 * Agents Fuse CLI command — F-Thread fusion execution
 *
 * Usage:
 *   morph-spec agents fuse --prompt "..." --count=3 --strategy=best-of-n [--feature=<f>]
 *   morph-spec agents review aggregate <feature> --agents=a1,a2,a3
 */

import chalk from 'chalk';
import { runFusion, aggregateResults, displayFusionSummary } from '../../lib/execution/fusion-executor.js';

export async function agentsFuseCommand(options) {
  if (!options.prompt) {
    console.error(chalk.red('--prompt is required'));
    process.exit(1);
  }

  const count = parseInt(options.count || '3', 10);
  const strategy = options.strategy || 'best-of-n';
  const feature = options.feature || 'fusion-session';
  const agents = options.agents ? options.agents.split(',').map(a => a.trim()) : null;

  console.log(chalk.cyan(`\n  F-Thread Fusion Execution\n`));
  console.log(`  Strategy:  ${strategy}`);
  console.log(`  Agents:    ${count}`);
  console.log(`  Feature:   ${feature}`);
  console.log(`  Prompt:    ${options.prompt.substring(0, 80)}${options.prompt.length > 80 ? '...' : ''}`);
  console.log('');

  try {
    const fusionSession = await runFusion(options.prompt, {
      feature,
      count,
      strategy,
      agents
    });

    console.log(chalk.cyan(`  ${fusionSession.threads.length} fusion threads spawned:\n`));
    for (let i = 0; i < fusionSession.threads.length; i++) {
      const thread = fusionSession.threads[i];
      const agent = fusionSession.agentConfigs[i];
      console.log(`  ${chalk.gray(thread.id.substring(0, 8))} — Agent: ${agent.agentId} (${thread.status})`);
    }

    console.log(chalk.yellow('\n  ⚠ Fusion threads spawned. To aggregate results:'));
    console.log(chalk.gray('  1. Execute each thread using the Task tool with the agent configs'));
    console.log(chalk.gray('  2. Collect results from each agent'));
    console.log(chalk.gray('  3. Run: morph-spec agents fuse-aggregate --results=<file> --strategy=' + strategy));
    console.log('');

    if (options.json) {
      console.log(JSON.stringify({
        threads: fusionSession.threads.map(t => ({ id: t.id, agent: t.agent, status: t.status })),
        agentConfigs: fusionSession.agentConfigs,
        strategy,
        feature
      }, null, 2));
    }
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}

export async function agentsReviewAggregateCommand(feature, options) {
  if (!options.agents) {
    console.error(chalk.red('--agents is required (comma-separated list)'));
    process.exit(1);
  }

  const agentList = options.agents.split(',').map(a => a.trim());
  const strategy = options.strategy || 'best-of-n';

  console.log(chalk.yellow('\n  ⚠ [STUB] This command returns mock data. Real aggregation not yet implemented.\n'));
  console.log(chalk.cyan(`  Aggregate Reviews — ${feature}\n`));
  console.log(`  Agents:   ${agentList.join(', ')}`);
  console.log(`  Strategy: ${strategy}`);
  console.log('');

  // Mock results for demo — in real usage, results come from agent output files
  const mockResults = agentList.map((agentId, i) => ({
    agentId,
    content: `Agent ${agentId} review for ${feature}`,
    checkpointsPassed: Math.floor(Math.random() * 3) + 2,
    checkpointsFailed: Math.floor(Math.random() * 2),
    errors: Math.floor(Math.random() * 2),
    warnings: Math.floor(Math.random() * 3)
  }));

  try {
    const aggregated = aggregateResults(mockResults, strategy);
    displayFusionSummary(aggregated);
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}
