/**
 * Thread Template CLI command — Thread type management
 *
 * Usage:
 *   morph-spec thread-template list
 *   morph-spec thread-template use <type> --feature=<feature>
 */

import chalk from 'chalk';
import { THREAD_TYPES } from '../../lib/threads/thread-manager.js';

const THREAD_TYPE_INFO = {
  [THREAD_TYPES.BASE]: {
    name: 'B-Thread (Base)',
    description: 'Standard single-agent thread. Sequential execution, all approval gates required.',
    useCase: 'Default for simple and medium features',
    phases: 'All standard phases',
    approvalGates: 'Manual (all)',
    maxConcurrent: 1
  },
  [THREAD_TYPES.PARALLEL]: {
    name: 'P-Thread (Parallel)',
    description: 'Multiple agents run simultaneously on different feature domains.',
    useCase: 'Full-stack features with independent backend/frontend/infra work',
    phases: 'All phases (parallel IMPLEMENT)',
    approvalGates: 'Manual (all)',
    maxConcurrent: 5
  },
  [THREAD_TYPES.FUSION]: {
    name: 'F-Thread (Fusion)',
    description: 'N agents independently generate solutions; best-of-N result is selected.',
    useCase: 'High-uncertainty decisions, critical architecture choices, prototype evaluation',
    phases: 'DESIGN → parallel IMPLEMENT → AGGREGATE → SYNC',
    approvalGates: 'Manual select (or auto best-of-n)',
    maxConcurrent: 3
  },
  [THREAD_TYPES.LONG_RUNNING]: {
    name: 'L-Thread (Long-Running)',
    description: 'Autonomous agent with stop hooks every 30 minutes for validation.',
    useCase: 'Large scope features (>10 files), autonomous implementation without interruption',
    phases: 'IMPLEMENT (continuous) with periodic validation',
    approvalGates: 'Auto (stop hooks validate)',
    maxConcurrent: 1
  },
  [THREAD_TYPES.ZERO_TOUCH]: {
    name: 'Z-Thread (Zero-Touch)',
    description: 'Fully autonomous execution. Auto-approves all gates, auto-commits on success.',
    useCase: 'Maximum-trust features with >95% checkpoint pass rate',
    phases: 'All phases (auto-approved)',
    approvalGates: 'Auto (trust-based)',
    maxConcurrent: 1
  }
};

export async function threadTemplateListCommand(options) {
  console.log(chalk.cyan('\n  Thread Types\n'));
  console.log('  ' + '─'.repeat(70));

  for (const [type, info] of Object.entries(THREAD_TYPE_INFO)) {
    console.log(`\n  ${chalk.bold(info.name)}`);
    console.log(`  ${info.description}`);
    console.log(`  ${chalk.gray('Use case:')} ${info.useCase}`);
    console.log(`  ${chalk.gray('Phases:')} ${info.phases}`);
    console.log(`  ${chalk.gray('Gates:')} ${info.approvalGates}`);
    console.log(`  ${chalk.gray('Max concurrent:')} ${info.maxConcurrent}`);
  }

  console.log('\n  ' + '─'.repeat(70));
  console.log(chalk.gray('\n  Set thread type: morph-spec thread-template use <type> --feature=<feature>\n'));
}

export async function threadTemplateUseCommand(type, options) {
  if (!options.feature) {
    console.error(chalk.red('--feature is required'));
    process.exit(1);
  }

  if (!THREAD_TYPE_INFO[type]) {
    console.error(chalk.red(`Unknown thread type: ${type}`));
    console.error(chalk.gray(`Valid types: ${Object.keys(THREAD_TYPE_INFO).join(', ')}`));
    process.exit(1);
  }

  const info = THREAD_TYPE_INFO[type];

  // Special checks
  if (type === THREAD_TYPES.ZERO_TOUCH) {
    console.log(chalk.yellow('\n  ⚠ Z-Thread requires maximum trust level (>95% checkpoint pass rate)'));
    console.log(chalk.gray('  Check trust: morph-spec trust status\n'));
  }

  // Update feature state with thread type
  try {
    const { updateFeature } = await import('../../core/state/state-manager.js');
    await updateFeature(options.feature, 'threadType', type);
    console.log(chalk.green(`\n  ✓ Thread type set: ${type} for feature: ${options.feature}`));
    console.log(`  ${info.name}: ${info.description}`);
    console.log('');
  } catch (err) {
    console.error(chalk.red(`  Error updating state: ${err.message}`));
    process.exit(1);
  }
}
