import { Command } from 'commander';
import chalk from 'chalk';
import { getFeature, setApprovalGate, getApprovalGate, getApprovalHistory } from '../../core/state/state-manager.js';

/**
 * Approval Commands - Manage approval gates for MORPH workflow
 *
 * Commands:
 * - approve: Mark a gate as approved
 * - reject: Reject a gate with reason
 * - approval-status: Show approval status for all gates
 */

const program = new Command();

/**
 * Valid approval gate names
 */
const VALID_GATES = ['proposal', 'uiux', 'design', 'tasks'];

/**
 * Approve action function - Mark a gate as approved
 */
export async function approveCommand(featureName, gateName, options = {}) {
  try {
    // Validate gate name
    if (!VALID_GATES.includes(gateName)) {
      console.error(chalk.red(`\n❌ Invalid gate: ${gateName}`));
      console.log(chalk.gray(`Valid gates: ${VALID_GATES.join(', ')}\n`));
      process.exit(1);
    }

    // Get feature state
    const feature = getFeature(featureName);
    if (!feature) {
      console.error(chalk.red(`\n❌ Feature not found: ${featureName}\n`));
      process.exit(1);
    }

    // Check if already approved
    const currentStatus = getApprovalGate(featureName, gateName);
    if (currentStatus?.approved) {
      console.log(chalk.yellow(`\n⚠️  Gate "${gateName}" is already approved`));
      console.log(chalk.gray(`Approved at: ${currentStatus.timestamp}`));
      console.log(chalk.gray(`Approved by: ${currentStatus.approvedBy || 'Unknown'}\n`));
      return;
    }

    // Set approval
    setApprovalGate(featureName, gateName, true, {
      approvedBy: options.approver || process.env.USER || process.env.USERNAME || 'user',
      approvedAt: new Date().toISOString(),
      notes: options.notes
    });

    console.log(chalk.green(`\n✅ Gate "${gateName}" approved for feature: ${featureName}`));
    console.log(chalk.gray(`Workflow can now proceed past ${gateName} phase\n`));

  } catch (error) {
    console.error(chalk.red(`\n❌ Error approving gate: ${error.message}\n`));
    process.exit(1);
  }
}

/**
 * Approve command - Mark a gate as approved
 */
program
  .command('approve <feature> <gate>')
  .description('Approve a phase gate to allow workflow progression')
  .action(approveCommand);

/**
 * Reject action function - Reject a gate with optional reason
 */
export async function rejectCommand(featureName, gateName, reason, options = {}) {
  try {
    // Validate gate name
    if (!VALID_GATES.includes(gateName)) {
      console.error(chalk.red(`\n❌ Invalid gate: ${gateName}`));
      console.log(chalk.gray(`Valid gates: ${VALID_GATES.join(', ')}\n`));
      process.exit(1);
    }

    // Get feature state
    const feature = getFeature(featureName);
    if (!feature) {
      console.error(chalk.red(`\n❌ Feature not found: ${featureName}\n`));
      process.exit(1);
    }

    // Set rejection
    setApprovalGate(featureName, gateName, false, {
      rejectedBy: process.env.USER || process.env.USERNAME || 'user',
      rejectedAt: new Date().toISOString(),
      reason: reason || 'No reason provided'
    });

    console.log(chalk.red(`\n❌ Gate "${gateName}" rejected for feature: ${featureName}`));
    if (reason) {
      console.log(chalk.gray(`Reason: ${reason}`));
    }
    console.log(chalk.yellow(`\n⚠️  Address the concerns and request approval again\n`));

  } catch (error) {
    console.error(chalk.red(`\n❌ Error rejecting gate: ${error.message}\n`));
    process.exit(1);
  }
}

/**
 * Reject command - Reject a gate with optional reason
 */
program
  .command('reject <feature> <gate> [reason]')
  .description('Reject a phase gate with optional reason')
  .action(rejectCommand);

/**
 * Approval status action function - Show all gates and their status
 */
export async function approvalStatusCommand(featureName, options = {}) {
  try {
    // Get feature state
    const feature = getFeature(featureName);
    if (!feature) {
      console.error(chalk.red(`\n❌ Feature not found: ${featureName}\n`));
      process.exit(1);
    }

    // JSON output
    if (options.json) {
      const status = {
        feature: featureName,
        phase: feature.phase,
        status: feature.status,
        gates: {}
      };

      for (const gateName of VALID_GATES) {
        status.gates[gateName] = getApprovalGate(featureName, gateName) || { approved: false };
      }

      console.log(JSON.stringify(status, null, 2));
      return;
    }

    console.log(chalk.bold(`\n📋 Approval Status for: ${featureName}`));
    console.log('━'.repeat(60));

    // Show current phase
    console.log(chalk.cyan(`\nCurrent Phase: ${feature.phase || 'unknown'}`));
    console.log(chalk.gray(`Feature Status: ${feature.status || 'unknown'}\n`));

    // Show each gate
    console.log(chalk.bold('Approval Gates:'));

    for (const gateName of VALID_GATES) {
      const gateStatus = getApprovalGate(featureName, gateName);

      if (!gateStatus) {
        console.log(`  ${chalk.gray('○')} ${gateName}: ${chalk.gray('Not yet evaluated')}`);
        continue;
      }

      if (gateStatus.approved) {
        console.log(`  ${chalk.green('✓')} ${gateName}: ${chalk.green('Approved')}`);
        if (gateStatus.timestamp) {
          console.log(chalk.gray(`      Approved at: ${gateStatus.timestamp}`));
        }
        if (gateStatus.approvedBy) {
          console.log(chalk.gray(`      Approved by: ${gateStatus.approvedBy}`));
        }
      } else {
        console.log(`  ${chalk.red('✗')} ${gateName}: ${chalk.red('Rejected / Not Approved')}`);
        if (gateStatus.reason) {
          console.log(chalk.gray(`      Reason: ${gateStatus.reason}`));
        }
        if (gateStatus.timestamp) {
          console.log(chalk.gray(`      Rejected at: ${gateStatus.timestamp}`));
        }
      }
    }

    // Show approval history if available
    const history = getApprovalHistory(featureName);
    if (history && history.length > 0) {
      console.log(chalk.bold('\nApproval History:'));
      history.slice(-5).forEach(entry => {
        const status = entry.approved ? chalk.green('✓ Approved') : chalk.red('✗ Rejected');
        console.log(`  ${status} ${entry.gate} - ${entry.timestamp}`);
      });
    }

    console.log('\n' + '━'.repeat(60) + '\n');

  } catch (error) {
    console.error(chalk.red(`\n❌ Error showing approval status: ${error.message}\n`));
    process.exit(1);
  }
}

/**
 * Approval status command - Show all gates and their status
 */
program
  .command('approval-status <feature>')
  .alias('status')
  .description('Show approval status for all gates')
  .action(approvalStatusCommand);

// Only parse if run directly (not imported as module)
if (import.meta.url === `file://${process.argv[1]}`) {
  if (process.argv.length > 2) {
    program.parse(process.argv);
  } else {
    program.help();
  }
}

export default program;
