/**
 * Trust CLI — Trust level management for zero-touch execution
 *
 * Usage:
 *   morph-spec trust status [feature]
 *   morph-spec trust set <feature> <level> [reason]
 *   morph-spec trust history
 *   morph-spec trust auto-calculate <feature>
 */

import chalk from 'chalk';
import {
  getTrust,
  setTrust,
  clearTrustOverride,
  getTrustHistory,
  autoCalculateTrust,
  TRUST_THRESHOLDS,
  AUTO_APPROVE_GATES
} from '../../lib/trust/trust-manager.js';

/**
 * Trust status — current trust level for a feature or all features
 */
export async function trustStatusCommand(featureName, options) {
  if (featureName) {
    const trust = getTrust(featureName);

    console.log(chalk.bold(`\n  Trust Status — ${featureName}`));
    console.log('  ' + '─'.repeat(50));

    const levelColor = trust.level === 'maximum' ? chalk.green
      : trust.level === 'high' ? chalk.cyan
      : trust.level === 'medium' ? chalk.yellow
      : chalk.red;

    console.log(`  Level:       ${levelColor(trust.level.toUpperCase())}`);
    console.log(`  Pass Rate:   ${Math.round((trust.passRate || 0) * 100)}%`);
    console.log(`  Checkpoints: ${trust.passed || 0}/${trust.total || 0} passed`);
    console.log(`  Source:      ${trust.source || 'calculated'}`);

    if (trust.source === 'manual') {
      console.log(chalk.yellow(`  Override:    ${trust.overrideReason || 'No reason provided'}`));
    }

    console.log(`\n  Auto-approved gates:`);
    if (trust.autoApprove.length === 0) {
      console.log(chalk.gray('    (none — manual approval required for all gates)'));
    } else {
      trust.autoApprove.forEach(g => console.log(chalk.green(`    ✓ ${g}`)));
    }

    console.log(`\n  Trust thresholds:`);
    for (const [level, threshold] of Object.entries(TRUST_THRESHOLDS)) {
      const gates = AUTO_APPROVE_GATES[level] || [];
      const marker = trust.level === level ? chalk.bold(' ← current') : '';
      console.log(`    ${level.padEnd(10)} ≥ ${Math.round(threshold * 100)}%  auto-approves: ${gates.join(', ') || 'none'}${marker}`);
    }

    console.log();
  } else {
    // Show all features
    const history = getTrustHistory();
    if (history.length === 0) {
      console.log(chalk.yellow('\n  No features found.\n'));
      return;
    }

    console.log(chalk.bold('\n  Trust Overview'));
    console.log('  ' + '─'.repeat(70));
    console.log(`  ${'Feature'.padEnd(25)} ${'Level'.padEnd(10)} ${'Pass%'.padEnd(8)} ${'CPs'.padEnd(8)} Phase`);
    console.log('  ' + '─'.repeat(70));

    for (const f of history) {
      const levelColor = f.level === 'maximum' ? chalk.green
        : f.level === 'high' ? chalk.cyan
        : f.level === 'medium' ? chalk.yellow
        : chalk.red;

      console.log(
        `  ${f.feature.padEnd(25)} ` +
        `${levelColor(f.level.padEnd(10))} ` +
        `${String(Math.round(f.passRate * 100) + '%').padEnd(8)} ` +
        `${String(f.checkpointsTotal).padEnd(8)} ` +
        `${f.phase || 'N/A'}`
      );
    }
    console.log();
  }
}

/**
 * Trust set — manually override trust level
 */
export async function trustSetCommand(featureName, level, reason, options) {
  if (!featureName || !level) {
    console.error(chalk.red('Usage: morph-spec trust set <feature> <level> [reason]'));
    console.error(chalk.gray('Levels: low, medium, high, maximum'));
    process.exit(1);
  }

  const effectiveReason = reason || `Manual override to ${level}`;

  try {
    const result = setTrust(featureName, level, effectiveReason);

    console.log(chalk.green(`\n✓ Trust updated for ${featureName}`));
    console.log(`  Level:         ${result.level}`);
    console.log(`  Auto-approves: ${result.autoApprove.join(', ') || 'none'}`);
    console.log(`  Reason:        ${result.reason}`);
    console.log(chalk.gray('\n  Note: Use "trust auto-calculate" to revert to calculated trust.\n'));
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}

/**
 * Trust history — table of all features with checkpoint pass rates
 */
export async function trustHistoryCommand(options) {
  const history = getTrustHistory();

  console.log(chalk.bold('\n  Trust History'));
  console.log('  ' + '─'.repeat(80));

  if (history.length === 0) {
    console.log(chalk.gray('  No features found.\n'));
    return;
  }

  for (const f of history) {
    const levelColor = f.level === 'maximum' ? chalk.green
      : f.level === 'high' ? chalk.cyan
      : f.level === 'medium' ? chalk.yellow
      : chalk.red;

    console.log(`\n  ${chalk.bold(f.feature)}`);
    console.log(`    Trust:       ${levelColor(f.level)} (${Math.round(f.passRate * 100)}% pass rate)`);
    console.log(`    Checkpoints: ${f.checkpointsPassed}/${f.checkpointsTotal} passed`);
    console.log(`    Phase:       ${f.phase || 'N/A'} | Status: ${f.status || 'N/A'}`);
    console.log(`    Source:      ${f.source}`);

    if (f.autoApprove.length > 0) {
      console.log(`    Auto-approves: ${chalk.green(f.autoApprove.join(', '))}`);
    }
  }

  console.log('\n  ' + '─'.repeat(80));
  console.log(chalk.gray(`  Total features: ${history.length}\n`));
}

/**
 * Trust auto-calculate — recalculate from checkpoint history
 */
export async function trustAutoCalculateCommand(featureName, options) {
  if (!featureName) {
    console.error(chalk.red('Usage: morph-spec trust auto-calculate <feature>'));
    process.exit(1);
  }

  try {
    const result = autoCalculateTrust(featureName);

    const levelColor = result.level === 'maximum' ? chalk.green
      : result.level === 'high' ? chalk.cyan
      : result.level === 'medium' ? chalk.yellow
      : chalk.red;

    console.log(chalk.bold(`\n  Trust Calculated — ${featureName}`));
    console.log('  ' + '─'.repeat(40));
    console.log(`  Level:         ${levelColor(result.level.toUpperCase())}`);
    console.log(`  Pass Rate:     ${Math.round(result.passRate * 100)}%`);
    console.log(`  Checkpoints:   ${result.passed}/${result.total} passed`);
    console.log(`  Auto-approves: ${result.autoApprove.join(', ') || 'none'}`);

    if (result.level === 'maximum') {
      console.log(chalk.green('\n  ✓ Feature is eligible for zero-touch execution!'));
      console.log(chalk.gray('  All gates will be auto-approved.\n'));
    } else {
      const nextLevel = result.passRate < TRUST_THRESHOLDS.medium ? 'medium'
        : result.passRate < TRUST_THRESHOLDS.high ? 'high'
        : 'maximum';
      const needed = Math.ceil(TRUST_THRESHOLDS[nextLevel] * result.total) - result.passed;
      console.log(chalk.gray(`\n  Next level: ${nextLevel} (need ${needed} more passing checkpoints)\n`));
    }
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}

/**
 * Trust clear — remove manual override
 */
export async function trustClearCommand(featureName, options) {
  if (!featureName) {
    console.error(chalk.red('Usage: morph-spec trust clear <feature>'));
    process.exit(1);
  }

  clearTrustOverride(featureName);
  console.log(chalk.green(`\n✓ Manual trust override cleared for ${featureName}`));
  console.log(chalk.gray('  Trust will now be calculated from checkpoint history.\n'));
}
