/**
 * Micro Agent CLI command
 *
 * Usage:
 *   morph-spec micro-agent create <name> --base-agent=<agent> --mission="..." [--standards=file1,file2]
 *   morph-spec micro-agent list
 *   morph-spec micro-agent show <name>
 */

import chalk from 'chalk';
import {
  createMicroAgent, saveMicroAgent, listMicroAgents, getMicroAgent
} from '../../lib/agents/micro-agent-factory.js';

export async function microAgentCreateCommand(name, options) {
  try {
    if (!options.baseAgent) {
      console.error(chalk.red('--base-agent is required'));
      process.exit(1);
    }
    if (!options.mission) {
      console.error(chalk.red('--mission is required'));
      process.exit(1);
    }

    const standards = options.standards ? options.standards.split(',').map(s => s.trim()) : [];

    const agent = createMicroAgent({
      name,
      baseAgent: options.baseAgent,
      standards,
      mission: options.mission,
      tools: options.tools ? options.tools.split(',').map(t => t.trim()) : null
    });

    const filePath = saveMicroAgent(agent);

    console.log(chalk.green(`\n  ✓ Micro-agent created: ${name}`));
    console.log(`  Base agent: ${options.baseAgent}`);
    console.log(`  Standards: ${standards.length > 0 ? standards.join(', ') : '(none)'}`);
    console.log(`  Context estimate: ${agent.contextEstimate.total.toLocaleString()} tokens`);
    console.log(`  Saved to: ${chalk.gray(filePath)}`);
    console.log('');
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}

export async function microAgentListCommand(options) {
  try {
    const agents = listMicroAgents();

    if (agents.length === 0) {
      console.log(chalk.gray('\n  No micro-agents found. Create one with: morph-spec micro-agent create\n'));
      return;
    }

    console.log(chalk.cyan(`\n  Micro-Agents (${agents.length})\n`));
    console.log('  ' + 'Name'.padEnd(20) + ' ' + 'Base'.padEnd(20) + ' ' + 'Standards'.padEnd(12) + ' ' + 'Context');
    console.log('  ' + '─'.repeat(70));

    for (const agent of agents) {
      console.log(
        '  ' +
        agent.id.padEnd(20) + ' ' +
        (agent.baseAgent || '—').padEnd(20) + ' ' +
        String(agent.standards).padEnd(12) + ' ' +
        `${(agent.contextEstimate / 1000).toFixed(1)}K tokens`
      );
    }
    console.log('');
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}

export async function microAgentShowCommand(name, options) {
  try {
    const agent = getMicroAgent(name);
    if (!agent) {
      console.error(chalk.red(`Micro-agent not found: ${name}`));
      process.exit(1);
    }

    console.log(chalk.cyan(`\n  Micro-Agent: ${name}\n`));
    console.log(`  Base agent:  ${agent.baseAgent}`);
    console.log(`  Domain:      ${agent.domain}`);
    console.log(`  Created:     ${agent.createdAt}`);
    console.log(`\n  Mission:\n  ${agent.mission}`);

    if (agent.standards?.length > 0) {
      console.log('\n  Standards:');
      agent.standards.forEach(s => console.log(`    - ${s}`));
    }

    console.log('\n  Context estimate:');
    console.log(`    Standards: ${agent.contextEstimate?.standards?.toLocaleString() || 0} tokens`);
    console.log(`    Overhead:  ${agent.contextEstimate?.overhead?.toLocaleString() || 0} tokens`);
    console.log(`    Total:     ${agent.contextEstimate?.total?.toLocaleString() || 0} tokens`);

    if (options.showPrompt) {
      console.log(chalk.cyan('\n  Generated Prompt:'));
      console.log(agent.prompt);
    }
    console.log('');
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}
