#!/usr/bin/env node

import { program } from 'commander';
import chalk from 'chalk';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { readFileSync } from 'fs';
import { setGlobalStack } from '../src/lib/stacks/stack-resolver.js';

// Project commands
import { initCommand } from '../src/commands/project/init.js';
import { updateCommand } from '../src/commands/project/update.js';
import { doctorCommand } from '../src/commands/project/doctor.js';
import { detectCommand } from '../src/commands/project/detect.js';
import { detectAgentsCommand } from '../src/commands/project/detect-agents.js';
import { detectWorkflowCommand } from '../src/commands/project/detect-workflow.js';
import { syncCommand } from '../src/commands/project/sync.js';

// Feature commands
import { createStoryCommand } from '../src/commands/feature/create-story.js';
import { shardSpecCommand } from '../src/commands/feature/shard-spec.js';
import { sprintStatusCommand } from '../src/commands/feature/sprint-status.js';

// State commands
import { stateCommand } from '../src/commands/state/state.js';
import { validatePhaseCommand } from '../src/commands/state/validate-phase.js';
import { rollbackPhaseCommand } from '../src/commands/state/rollback-phase.js';
import { advancePhaseCommand } from '../src/commands/state/advance-phase.js';
import { approveCommand, rejectCommand, approvalStatusCommand } from '../src/commands/state/approve.js';

// Task commands
import { taskDoneCommand, taskStartCommand, taskNextCommand } from '../src/commands/tasks/task.js';

// Generation commands
import { generateDesignSystemCommand, generateMetadataCommand } from '../src/commands/generation/generate.js';
import { generateContextCommand } from '../src/commands/generation/generate-context.js';

// Validation commands
import { validateCommand } from './validate.js';
import { validateBlazorCommand } from '../src/commands/validation/validate-blazor.js';
import { lintFluentCommand } from '../src/commands/validation/lint-fluent.js';
import { analyzeBlazorConcurrencyCommand } from '../src/commands/validation/analyze-blazor-concurrency.js';
import { validateBlazorStateCommand } from '../src/commands/validation/validate-blazor-state.js';
import { validateCssCommand } from '../src/commands/validation/validate-css.js';

// Template commands
import { templateListCommand } from '../src/commands/templates/template-list.js';
import { templateShowCommand } from '../src/commands/templates/template-show.js';
import { templateRenderCommand } from '../src/commands/templates/template-render.js';
import { templateCustomizeCommand } from '../src/commands/templates/template-customize.js';
import { templateValidateCommand } from '../src/commands/templates/template-validate.js';

// Agent commands
import { spawnTeamCommand } from '../src/commands/agents/spawn-team.js';

// Learning commands
import capturePatternProgram from '../src/commands/learning/capture-pattern.js';
import searchPatternsProgram from '../src/commands/learning/search-patterns.js';

// Utility commands
import troubleshootCommand from '../src/commands/utils/troubleshoot.js';
import { sessionSummaryCommand } from '../src/commands/utils/session-summary.js';

// Thread, Analytics, Core Four commands
import {
  threadsListCommand, threadsStatusCommand, threadsKillCommand,
  threadsAnalyticsCommand, threadsWaitAllCommand, threadsWaitAnyCommand
} from '../src/commands/threads/threads.js';
import {
  analyticsFeatureCommand, analyticsContextCommand, analyticsProjectCommand
} from '../src/commands/analytics/analytics.js';
import { coreFourCommand } from '../src/commands/context/core-four.js';

// Context Optimization commands
import { mcpOptimizeCommand, mcpListCommand } from '../src/commands/mcp/mcp.js';
import {
  microAgentCreateCommand, microAgentListCommand, microAgentShowCommand
} from '../src/commands/agents/micro-agent.js';
import { contextPrimeCommand } from '../src/commands/context/context-prime.js';

// Parallelization commands
import {
  squadTemplateListCommand, squadTemplateUseCommand, squadTemplateShowCommand
} from '../src/commands/agents/squad-template.js';
import {
  threadTemplateListCommand, threadTemplateUseCommand
} from '../src/commands/threads/thread-template.js';
import { spawnTeamParallelCommand } from '../src/commands/agents/spawn-team.js';

// Fusion commands
import { agentsFuseCommand, agentsReviewAggregateCommand } from '../src/commands/agents/agents-fuse.js';

// Meta-Prompts (HOP) commands
import { hopRenderCommand, hopListCommand } from '../src/commands/templates/template-render.js';

// Trust commands
import {
  trustStatusCommand, trustSetCommand, trustHistoryCommand,
  trustAutoCalculateCommand, trustClearCommand
} from '../src/commands/trust/trust.js';

// Libraries
import { LearningSystem } from '../src/lib/learning/learning-system.js';

const __dirname = dirname(fileURLToPath(import.meta.url));
const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf8'));

const banner = chalk.cyan(`
  ███╗   ███╗ ██████╗ ██████╗ ██████╗ ██╗  ██╗
  ████╗ ████║██╔═══██╗██╔══██╗██╔══██╗██║  ██║
  ██╔████╔██║██║   ██║██████╔╝██████╔╝███████║
  ██║╚██╔╝██║██║   ██║██╔══██╗██╔═══╝ ██╔══██║
  ██║ ╚═╝ ██║╚██████╔╝██║  ██║██║     ██║  ██║
  ╚═╝     ╚═╝ ╚═════╝ ╚═╝  ╚═╝╚═╝     ╚═╝  ╚═╝

  Methodical Orchestration for Reliable Production-ready SPEC-driven development
  by Polymorphism Tech | v${pkg.version}
`);

program
  .name('morph-spec')
  .description('MORPH-SPEC Framework CLI')
  .version(pkg.version)
  .option('--stack <stack>', 'Override stack detection (blazor-azure | nextjs-supabase)')
  .addHelpText('beforeAll', banner);

program
  .command('init')
  .description('Initialize MORPH-SPEC in current directory')
  .option('-f, --force', 'Overwrite existing MORPH installation')
  .option('-p, --path <path>', 'Target path (default: current directory)')
  .action(initCommand);

program
  .command('update')
  .description('Update MORPH templates and standards to latest version')
  .option('--templates', 'Update only templates')
  .option('--standards', 'Update only standards')
  .action(updateCommand);

program
  .command('doctor')
  .description('Check MORPH installation health')
  .option('--full', 'Run full health check (lib files, commands, HOPs, standards, agents, state)')
  .action(doctorCommand);

program
  .command('detect')
  .description('Detect project stack, architecture, and patterns')
  .option('-p, --path <path>', 'Project path (default: current directory)')
  .option('-v, --verbose', 'Show detailed detection results')
  .option('--no-save', 'Do not save results to .morph/project/')
  .action(detectCommand);

program
  .command('detect-agents <input...>')
  .description('Detect which agents to activate based on keywords in user input')
  .option('-v, --verbose', 'Show detailed detection results')
  .option('-j, --json', 'Output full result as JSON')
  .option('-i, --ids-only', 'Output only agent IDs (one per line)')
  .action(detectAgentsCommand);

program
  .command('detect-workflow <input...>')
  .description('Detect appropriate workflow for a feature request')
  .option('-v, --verbose', 'Show detailed detection reasoning')
  .option('-j, --json', 'Output as JSON')
  .option('-p, --project-path <path>', 'Project path (default: current directory)')
  .action(detectWorkflowCommand);

program
  .command('sync')
  .description('Sync standards from feature decisions')
  .option('-p, --path <path>', 'Project path (default: current directory)')
  .option('--dry-run', 'Show what would be synced without updating files')
  .action(syncCommand);

// Story-driven development commands
const storyCommand = program
  .command('story')
  .description('Story-driven development commands');

storyCommand
  .command('create <feature> <story-id>')
  .description('Create a new story with auto-injected Dev Notes')
  .option('--title <title>', 'Story title')
  .option('--epic <epic>', 'Epic name')
  .option('--context <context>', 'Story context')
  .option('--tasks <tasks>', 'Comma-separated tasks')
  .option('--dry-run', 'Preview without writing file')
  .action(createStoryCommand);

storyCommand
  .command('shard <feature>')
  .description('Shard spec.md into manageable chunks (90% token savings)')
  .option('--dry-run', 'Preview shards without writing files')
  .option('--verbose', 'Show detailed shard info')
  .action(shardSpecCommand);

storyCommand
  .command('status <feature> [action] [story-id]')
  .description('Manage sprint status (show | start | qa | done | next)')
  .action(sprintStatusCommand);

// State management commands
program
  .command('state <action> [args...]')
  .description('Manage state.json (init | get | set | checkpoint | list | add-agent | remove-agent | mark-output)')
  .option('--force', 'Force overwrite (init command)')
  .option('--project <name>', 'Project name (init command)')
  .option('--type <type>', 'Project type (init command)')
  .option('--json', 'Output as JSON (get command)')
  .action((action, args, options) => stateCommand(action, args, options));

// Task management commands (MORPH-SPEC 3.0)
const taskCommand = program
  .command('task')
  .description('Manage feature tasks (done | start | next)');

taskCommand
  .command('done <feature> <task-ids...>')
  .description('Mark tasks as completed (runs validation first)')
  .option('--skip-validation', 'Skip code validation (not recommended)')
  .action((feature, taskIds, options) => taskDoneCommand(feature, taskIds, options));

taskCommand
  .command('start <feature> <task-id>')
  .description('Start a task (mark as in_progress)')
  .action((feature, taskId, options) => taskStartCommand(feature, taskId, options));

taskCommand
  .command('next <feature>')
  .description('Show next suggested task')
  .action((feature, options) => taskNextCommand(feature, options));

// Generation commands
const generateCommand = program
  .command('generate')
  .description('Generate code from templates');

generateCommand
  .command('design-system <ui-design-system-md>')
  .description('Generate CSS + theme files from ui-design-system.md')
  .option('--fluent', 'Generate only Fluent UI theme')
  .option('--mud', 'Generate only MudBlazor theme')
  .option('--both', 'Generate both themes (default)')
  .option('--namespace <ns>', 'C# namespace (default: YourProject.Themes)')
  .option('--css-output <path>', 'CSS output path (default: wwwroot/css/design-system.css)')
  .option('--fluent-output <path>', 'Fluent theme output path (default: Themes/FluentDesignTheme.cs)')
  .option('--mud-output <path>', 'MudBlazor theme output path (default: Themes/MudDesignTheme.cs)')
  .option('--dry-run', 'Preview without writing files')
  .action(generateDesignSystemCommand);

generateCommand
  .command('recap <feature>')
  .description('Auto-generate recap.md from project data (state, validation, contracts)')
  .option('--quiet', 'Suppress output')
  .action(async (feature, options) => {
    const { generateRecap } = await import('../src/lib/generators/recap-generator.js');
    await generateRecap('.', feature, options);
  });

generateCommand
  .command('context [feature]')
  .description('Generate CONTEXT.md with full project data for Claude Code')
  .action(async (feature) => {
    await generateContextCommand('.', feature);
  });

generateCommand
  .command('metadata <feature>')
  .description('Generate metadata.json summary from markdown outputs')
  .option('--output <path>', 'Custom output path')
  .option('--verbose', 'Show detailed extraction info')
  .action((feature, options) => generateMetadataCommand(feature, options));

// Validation commands (Sprint 4: Continuous Validation)
program
  .command('validate [validator]')
  .description('Run project validations (all | packages | architecture | contrast)')
  .option('-v, --verbose', 'Show detailed output')
  .option('--auto-fix, --fix', 'Auto-fix issues where possible')
  .option('--no-fail', 'Don\'t exit with error code')
  .option('-i, --insights', 'Show learning insights')
  .option('--wcag-aaa', 'Use WCAG AAA standard (stricter)')
  .action((validator, options) => {
    const args = validator ? [validator] : ['all'];
    if (options.verbose) args.push('--verbose');
    if (options.autoFix) args.push('--auto-fix');
    if (options.noFail) args.push('--no-fail');
    if (options.insights) args.push('--insights');
    if (options.wcagAaa) args.push('--wcag-aaa');
    validateCommand(args);
  });

// Fluent UI Blazor validation commands
program
  .command('validate-blazor [path]')
  .description('Validate Fluent UI Blazor patterns and icons')
  .option('-v, --verbose', 'Show detailed output')
  .option('--fix', 'Auto-fix issues where possible')
  .action(validateBlazorCommand);

program
  .command('lint-fluent [path]')
  .description('Lint Fluent UI patterns for common issues')
  .option('-v, --verbose', 'Show detailed output')
  .action(lintFluentCommand);

program
  .command('analyze-blazor-concurrency [path]')
  .description('Analyze Blazor Server code for DbContext concurrency issues')
  .option('-v, --verbose', 'Show detailed output')
  .action(analyzeBlazorConcurrencyCommand);

program
  .command('validate-blazor-state [path]')
  .description('Validate Blazor Server session state patterns')
  .option('-v, --verbose', 'Show detailed output')
  .action(validateBlazorStateCommand);

program
  .command('validate-css [path]')
  .description('Validate CSS classes used in Razor files exist in CSS files')
  .option('-v, --verbose', 'Show detailed output')
  .option('--generate-stub', 'Generate a CSS stub file with missing classes')
  .option('--include-utilities', 'Include utility classes (Tailwind, Bootstrap) in validation')
  .action(validateCssCommand);

// Learning commands (Sprint 4: Learning System)
const learnCommand = program
  .command('learn')
  .description('AI learning system commands');

learnCommand
  .command('analyze')
  .description('Learn from project history (decisions.md files)')
  .option('-v, --verbose', 'Show detailed learning progress')
  .action(async (options) => {
    const learner = new LearningSystem('.');
    await learner.learnFromProject();

    if (options.verbose) {
      learner.formatInsights();
    }
  });

learnCommand
  .command('insights')
  .description('Show AI insights and patterns')
  .option('--json', 'Output as JSON')
  .action((options) => {
    const learner = new LearningSystem('.');

    if (options.json) {
      console.log(JSON.stringify(learner.getInsightsSummary(), null, 2));
    } else {
      learner.formatInsights();
    }
  });

learnCommand
  .command('suggest [category]')
  .description('Get AI suggestions for a category (uiLibrary | architecture | infrastructure | authentication | stateManagement | testing)')
  .option('--json', 'Output as JSON')
  .action((category, options) => {
    const learner = new LearningSystem('.');

    if (category) {
      const suggestion = learner.getSuggestion(category);
      if (options.json) {
        console.log(JSON.stringify(suggestion, null, 2));
      } else {
        console.log(chalk.cyan(`\n💡 Suggestion for ${category}:\n`));
        if (suggestion.confidence === 'none') {
          console.log(chalk.yellow(`   ${suggestion.reason}`));
        } else {
          console.log(chalk.white(`   → ${suggestion.suggestion} (${suggestion.percentage}% confidence)`));
          console.log(chalk.gray(`     ${suggestion.reason}`));
        }
        console.log('');
      }
    } else {
      const suggestions = learner.getAllSuggestions();
      if (options.json) {
        console.log(JSON.stringify(suggestions, null, 2));
      } else {
        learner.formatSuggestions(suggestions);
      }
    }
  });

learnCommand
  .command('reset')
  .description('Reset knowledge base (clear all learned patterns)')
  .option('--force', 'Skip confirmation')
  .action((options) => {
    if (!options.force) {
      console.log(chalk.yellow('\n⚠️  This will delete all learned patterns and preferences.'));
      console.log(chalk.gray('   Run with --force to confirm.\n'));
      process.exit(1);
    }

    const learner = new LearningSystem('.');
    learner.reset();
    console.log(chalk.green('\n✅ Knowledge base reset\n'));
  });

// Template management commands
const templateCommand = program
  .command('template')
  .description('Template management (list | show | render | customize | validate)');

templateCommand
  .command('list')
  .description('List all available templates')
  .option('--category <category>', 'Filter by category (documentation, code, infrastructure, context, examples)')
  .option('--phase <phase>', 'Filter by phase (proposal, design, implement, etc.)')
  .option('--stack <stack>', 'Filter by stack (blazor-azure, nextjs-supabase)')
  .option('--required', 'Show only required templates')
  .action(templateListCommand);

templateCommand
  .command('show <template-id>')
  .description('Show detailed information about a template')
  .option('--show-path', 'Show resolved template file path')
  .option('--preview', 'Show first 20 lines of template content')
  .option('--stack <stack>', 'Stack for path resolution (default: blazor-azure)')
  .option('--project-path <path>', 'Project path (default: current directory)')
  .action(templateShowCommand);

templateCommand
  .command('render <template-id> <output-path> <variables-json>')
  .description('Render a template with variables')
  .option('--dry-run', 'Preview without writing file')
  .option('--stack <stack>', 'Stack for template resolution (default: blazor-azure)')
  .option('--project-path <path>', 'Project path (default: current directory)')
  .option('-v, --verbose', 'Show detailed output')
  .action(templateRenderCommand);

templateCommand
  .command('customize <template-id>')
  .description('Copy framework template to project for customization')
  .option('--stack <stack>', 'Target stack (default: blazor-azure)')
  .option('--local', 'Copy to project .morph/templates/ instead of stack')
  .option('--force', 'Overwrite existing customized template')
  .option('--project-path <path>', 'Project path (default: current directory)')
  .option('-v, --verbose', 'Show detailed output')
  .action(templateCustomizeCommand);

templateCommand
  .command('validate [template-id]')
  .description('Validate template(s) for correct Handlebars syntax')
  .option('--category <category>', 'Validate templates in specific category')
  .option('--technology <technology>', 'Validate templates for specific technology')
  .option('--include-deprecated', 'Include deprecated templates')
  .option('--show-valid', 'Show valid templates in output')
  .option('--strict', 'Exit with error on warnings')
  .option('--project-path <path>', 'Project path (default: current directory)')
  .option('-v, --verbose', 'Show detailed validation information')
  .action(templateValidateCommand);

// HOP (Higher-Order Prompts) commands
const hopCommand = program
  .command('hop')
  .description('Higher-Order Prompts — render and manage meta-prompt templates');

hopCommand
  .command('list')
  .description('List all available HOP templates')
  .action(hopListCommand);

hopCommand
  .command('render <hop-id> [output-path]')
  .description('Render a HOP template with variables')
  .option('--variables <json>', 'Variables JSON string', '{}')
  .option('--dry-run', 'Preview without writing file')
  .action((hopId, outputPath, options) => hopRenderCommand(hopId, outputPath, options.variables, options));

// Trust commands
const trustCommand = program
  .command('trust')
  .description('Trust level management for zero-touch execution');

trustCommand
  .command('status [feature]')
  .description('Show trust level and auto-approval status')
  .action(trustStatusCommand);

trustCommand
  .command('set <feature> <level> [reason]')
  .description('Manually set trust level (low|medium|high|maximum)')
  .action(trustSetCommand);

trustCommand
  .command('history')
  .description('Show trust history for all features')
  .action(trustHistoryCommand);

trustCommand
  .command('auto-calculate <feature>')
  .description('Recalculate trust from checkpoint history')
  .action(trustAutoCalculateCommand);

trustCommand
  .command('clear <feature>')
  .description('Clear manual trust override (revert to calculated)')
  .action(trustClearCommand);

// Troubleshooting command
program
  .command('troubleshoot <keywords...>')
  .alias('ts')
  .description('Search troubleshooting solutions for common errors')
  .option('--category <cat>', 'Filter by category (blazor, efcore, azure, auth, deploy)')
  .option('-v, --verbose', 'Show full solution content')
  .option('--list-categories', 'List available categories')
  .action(troubleshootCommand);

// Phase management commands
const phaseCommand = program
  .command('phase')
  .description('Phase management (advance | validate)');

phaseCommand
  .command('advance <feature>')
  .description('Validate current phase and advance to next')
  .option('--skip-optional', 'Skip optional phases (uiux, sync)')
  .action((feature, options) => advancePhaseCommand(feature, options));

// Phase validation command (also available as standalone)
program
  .command('validate-phase <feature> <phase>')
  .description('Validate prerequisites before advancing to a phase')
  .option('-v, --verbose', 'Show detailed output')
  .action(validatePhaseCommand);

// Session summary command
program
  .command('session-summary <feature>')
  .alias('summary')
  .description('Show summary of current session (phases, decisions, progress)')
  .option('--json', 'Output as JSON')
  .action(sessionSummaryCommand);

// Rollback phase command
program
  .command('rollback <feature> <phase>')
  .description('Rollback feature to a previous phase (marks outputs as draft)')
  .option('--force', 'Skip confirmation')
  .option('-v, --verbose', 'Show detailed output')
  .action(rollbackPhaseCommand);

// Approval workflow commands
program
  .command('approve <feature> <gate>')
  .description('Approve a phase gate (design, tasks, uiux, proposal)')
  .option('--approver <name>', 'Name of approver (default: current user)')
  .option('--notes <notes>', 'Approval notes')
  .action((feature, gate, options) => approveCommand(feature, gate, options));

program
  .command('reject <feature> <gate> [reason]')
  .description('Reject a phase gate with optional reason')
  .action((feature, gate, reason, options) => rejectCommand(feature, gate, reason, options));

program
  .command('approval-status <feature>')
  .description('Show approval status for all gates')
  .option('--json', 'Output as JSON')
  .action((feature, options) => approvalStatusCommand(feature, options));

// Agent team spawning
program
  .command('spawn-team <feature>')
  .description('Generate agent team configuration for Task tool')
  .option('--json', 'Output as JSON')
  .option('--verbose', 'Show detailed team configuration')
  .action((feature, options) => spawnTeamCommand(feature, options));

// Pattern learning system - Add as subcommands
program.addCommand(capturePatternProgram);
program.addCommand(searchPatternsProgram);

// ─────────────────────────────────────────────────────────────────────────────
// Thread Management
// ─────────────────────────────────────────────────────────────────────────────
const threadsCommand = program
  .command('threads')
  .description('Thread lifecycle management');

threadsCommand
  .command('list')
  .description('List threads (optionally filtered by feature/status/type)')
  .option('--feature <feature>', 'Filter by feature name')
  .option('--status <status>', 'Filter by status (pending|running|completed|failed|killed)')
  .option('--type <type>', 'Filter by type (base|parallel|fusion|long-running|zero-touch)')
  .action((options) => threadsListCommand(options));

threadsCommand
  .command('status <id>')
  .description('Show detailed status of a thread')
  .action((id) => threadsStatusCommand(id));

threadsCommand
  .command('kill <id>')
  .description('Terminate a running thread')
  .action((id) => threadsKillCommand(id));

threadsCommand
  .command('analytics')
  .description('Show thread analytics dashboard for a feature')
  .option('--feature <feature>', 'Feature name (required)')
  .action((options) => threadsAnalyticsCommand(options));

threadsCommand
  .command('wait-all <feature>')
  .description('Block until all threads for a feature complete')
  .option('--timeout <minutes>', 'Timeout in minutes (default: 60)', '60')
  .action((feature, options) => threadsWaitAllCommand(feature, options));

threadsCommand
  .command('wait-any <feature>')
  .description('Block until any thread for a feature completes')
  .option('--timeout <minutes>', 'Timeout in minutes (default: 60)', '60')
  .action((feature, options) => threadsWaitAnyCommand(feature, options));

// ─────────────────────────────────────────────────────────────────────────────
// Analytics
// ─────────────────────────────────────────────────────────────────────────────
const analyticsCommand = program
  .command('analytics')
  .description('Metrics and analytics dashboards');

analyticsCommand
  .command('feature <name>')
  .description('Show thread analytics dashboard for a feature')
  .action((name, options) => analyticsFeatureCommand(name, options));

analyticsCommand
  .command('context <name>')
  .description('Show context token usage and optimization opportunities')
  .action((name, options) => analyticsContextCommand(name, options));

analyticsCommand
  .command('project')
  .description('Show project-wide analytics dashboard (30-day summary)')
  .option('--period <days>', 'Period in days (default: 30)', '30')
  .action((options) => analyticsProjectCommand(options));

// ─────────────────────────────────────────────────────────────────────────────
// Core Four
// ─────────────────────────────────────────────────────────────────────────────
program
  .command('core-four <feature>')
  .description('Show Core Four dashboard: Context/Model/Prompt/Tools')
  .option('--json', 'Output as JSON')
  .action((feature, options) => coreFourCommand(feature, options));

// ─────────────────────────────────────────────────────────────────────────────
// MCP Optimizer
// ─────────────────────────────────────────────────────────────────────────────
const mcpCommand = program
  .command('mcp')
  .description('MCP server analysis and optimization');

mcpCommand
  .command('optimize')
  .description('Analyze MCP servers and suggest optimizations')
  .action((options) => mcpOptimizeCommand(options));

mcpCommand
  .command('list')
  .description('List configured MCP servers with usage stats')
  .action((options) => mcpListCommand(options));

// ─────────────────────────────────────────────────────────────────────────────
// Micro Agents
// ─────────────────────────────────────────────────────────────────────────────
const microAgentCommand = program
  .command('micro-agent')
  .description('Create and manage ultra-specialized micro-agents');

microAgentCommand
  .command('create <name>')
  .description('Create a new micro-agent')
  .option('--base-agent <agent>', 'Base agent ID to specialize from')
  .option('--mission <mission>', 'Single focused mission for this agent')
  .option('--standards <files>', 'Comma-separated standards files to load (1-3 max)')
  .option('--tools <tools>', 'Comma-separated tools to allow (default: Read,Write,Edit)')
  .action((name, options) => microAgentCreateCommand(name, options));

microAgentCommand
  .command('list')
  .description('List all micro-agents')
  .action((options) => microAgentListCommand(options));

microAgentCommand
  .command('show <name>')
  .description('Show micro-agent details')
  .option('--show-prompt', 'Show the generated system prompt')
  .action((name, options) => microAgentShowCommand(name, options));

// ─────────────────────────────────────────────────────────────────────────────
// Context Prime
// ─────────────────────────────────────────────────────────────────────────────
program
  .command('prime [type]')
  .description('Output context priming file (feature|bug|refactor|design|infra)')
  .option('--json', 'Output as JSON')
  .action((type, options) => contextPrimeCommand(type, options));

// ─────────────────────────────────────────────────────────────────────────────
// Fusion (F-Thread)
// ─────────────────────────────────────────────────────────────────────────────
const agentsFuseCmd = program
  .command('agents-fuse')
  .description('F-Thread fusion execution: run N agents, aggregate best result');

agentsFuseCmd
  .command('run')
  .description('Run fusion: spawn N agents with same prompt, aggregate results')
  .option('--prompt <prompt>', 'Prompt/mission for all fusion agents (required)')
  .option('--count <n>', 'Number of agents to run (default: 3)', '3')
  .option('--strategy <strategy>', 'Aggregation strategy: best-of-n | consensus | manual-select', 'best-of-n')
  .option('--feature <feature>', 'Feature name for tracking')
  .option('--agents <list>', 'Comma-separated agent IDs to use')
  .option('--json', 'Output as JSON')
  .action((options) => agentsFuseCommand(options));

agentsFuseCmd
  .command('aggregate-reviews <feature>')
  .description('Aggregate review results from N agents')
  .option('--agents <list>', 'Comma-separated agent IDs (required)')
  .option('--strategy <strategy>', 'Aggregation strategy', 'best-of-n')
  .action((feature, options) => agentsReviewAggregateCommand(feature, options));

// ─────────────────────────────────────────────────────────────────────────────
// Squad Templates
// ─────────────────────────────────────────────────────────────────────────────
const squadTemplateCmd = program
  .command('squad-template')
  .description('Squad template management for parallel execution');

squadTemplateCmd
  .command('list')
  .description('List available squad templates')
  .action((options) => squadTemplateListCommand(options));

squadTemplateCmd
  .command('use <template-id>')
  .description('Configure a feature to use a squad template')
  .option('--feature <feature>', 'Feature name (required)')
  .action((id, options) => squadTemplateUseCommand(id, options));

squadTemplateCmd
  .command('show <template-id>')
  .description('Show squad template details')
  .option('--json', 'Output as JSON')
  .action((id, options) => squadTemplateShowCommand(id, options));

// ─────────────────────────────────────────────────────────────────────────────
// Commands — Thread Templates
// ─────────────────────────────────────────────────────────────────────────────
const threadTemplateCmd = program
  .command('thread-template')
  .description('Thread type management');

threadTemplateCmd
  .command('list')
  .description('List available thread types (B/P/F/L/Z-Thread)')
  .action((options) => threadTemplateListCommand(options));

threadTemplateCmd
  .command('use <type>')
  .description('Configure thread type for a feature')
  .option('--feature <feature>', 'Feature name (required)')
  .action((type, options) => threadTemplateUseCommand(type, options));

// Wire global --stack flag to stack-resolver before any command executes
program.hook('preAction', () => {
  const opts = program.opts();
  if (opts.stack) {
    setGlobalStack(opts.stack);
  }
});

program.parse();
