/**
 * MORPH-SPEC Detect Workflow Command
 *
 * Analyzes a feature request and detects the most appropriate workflow
 *
 * Usage:
 *   morph-spec detect-workflow "add pagination to users table"
 */

import chalk from 'chalk';
import { detectWorkflow, getWorkflowConfig } from '../../core/workflows/workflow-detector.js';

/**
 * Main command handler
 * @param {Array<string>} input - User request words
 * @param {Object} options - Command options
 */
export async function detectWorkflowCommand(input, options = {}) {
  const userRequest = input.join(' ');

  if (!userRequest || userRequest.trim().length === 0) {
    console.log(chalk.red('\n✗ Error: Please provide a feature request'));
    console.log(chalk.gray('\nUsage: morph-spec detect-workflow "add pagination to users table"\n'));
    process.exit(1);
  }

  console.log(chalk.cyan('\n╔════════════════════════════════════════════════╗'));
  console.log(chalk.cyan('║     MORPH-SPEC WORKFLOW DETECTION             ║'));
  console.log(chalk.cyan('╚════════════════════════════════════════════════╝\n'));

  console.log(chalk.gray('Analyzing request:'), `"${userRequest}"`);
  console.log('');

  try {
    // Detect workflow
    const result = await detectWorkflow({
      userRequest,
      projectPath: options.projectPath || '.'
    });

    // Load workflow config for details
    const workflowConfig = getWorkflowConfig(result.workflowId);

    if (options.json) {
      // JSON output mode
      console.log(JSON.stringify({
        workflowId: result.workflowId,
        workflowName: workflowConfig?.name || result.workflowId,
        confidence: result.confidence,
        matchedKeywords: result.matchedKeywords,
        estimatedComplexity: result.estimatedComplexity,
        reasoning: result.reasoning,
        alternativeWorkflows: result.alternativeWorkflows,
        workflowConfig: workflowConfig
      }, null, 2));
      return;
    }

    // Human-readable output
    const confidencePercent = Math.round(result.confidence * 100);
    console.log(chalk.green(`✓ Detected Workflow: ${chalk.bold(workflowConfig?.name || result.workflowId)}`));
    console.log(chalk.gray(`  Confidence: ${confidencePercent}%\n`));

    // Criteria Match
    console.log(chalk.cyan('Criteria Match:'));
    if (result.matchedKeywords.length > 0) {
      console.log(chalk.green(`  ✓ Keywords: ${result.matchedKeywords.join(', ')}`));
    }
    console.log(chalk.gray(`  • Estimated complexity: ${result.estimatedComplexity.files} files, ~${result.estimatedComplexity.lines} lines`));
    if (result.estimatedComplexity.components > 0) {
      console.log(chalk.gray(`  • Components: ${result.estimatedComplexity.components}`));
    }
    if (result.estimatedComplexity.hasInfra) {
      console.log(chalk.yellow(`  ⚠ Infrastructure keywords detected`));
    }
    console.log('');

    // Workflow Details
    if (workflowConfig) {
      console.log(chalk.cyan('Workflow Description:'));
      console.log(chalk.gray(`  ${workflowConfig.description}\n`));

      // Phases to Run
      console.log(chalk.cyan('Phases to Run:'));
      const phasesToRun = workflowConfig.phases.run || [];
      phasesToRun.forEach((phase, index) => {
        const pausePoint = workflowConfig.pausePoints?.find(p => p.phase === phase);
        const pauseIndicator = pausePoint ? chalk.yellow(' ⏸️  Pause for approval') : '';
        console.log(chalk.white(`  ${index + 1}. ${phase.toUpperCase()}${pauseIndicator}`));
        if (pausePoint) {
          console.log(chalk.gray(`     Question: "${pausePoint.question}"`));
        }
      });
      console.log('');

      // Phases Skipped
      if (workflowConfig.phases.skip && workflowConfig.phases.skip.length > 0) {
        console.log(chalk.cyan('Phases Skipped:'));
        workflowConfig.phases.skip.forEach(phase => {
          const reason = getSkipReason(phase, workflowConfig);
          console.log(chalk.gray(`  ✗ ${phase.toUpperCase()}${reason ? ` - ${reason}` : ''}`));
        });
        console.log('');
      }

      // Combined Phases
      if (workflowConfig.phases.combined && Object.keys(workflowConfig.phases.combined).length > 0) {
        console.log(chalk.cyan('Combined Phases:'));
        for (const [combinedName, phases] of Object.entries(workflowConfig.phases.combined)) {
          console.log(chalk.gray(`  → ${combinedName.toUpperCase()} combines: ${phases.join(', ')}`));
        }
        console.log('');
      }

      // Required Outputs
      if (workflowConfig.outputs?.required && workflowConfig.outputs.required.length > 0) {
        console.log(chalk.cyan('Required Outputs:'));
        workflowConfig.outputs.required.forEach(output => {
          console.log(chalk.white(`  • ${output}`));
        });
        console.log('');
      }
    }

    // Alternative Workflows
    if (result.alternativeWorkflows.length > 0) {
      console.log(chalk.cyan('Alternative Workflows:'));
      result.alternativeWorkflows.forEach(alt => {
        const altPercent = Math.round(alt.confidence * 100);
        console.log(chalk.gray(`  - ${alt.workflowId} (${altPercent}%): ${alt.reason}`));
      });
      console.log('');
    }

    // How to Override
    console.log(chalk.cyan('To override detected workflow:'));
    console.log(chalk.white(`  morph-spec state set <feature-name> workflow <workflow-id>`));
    console.log('');

    console.log(chalk.gray('─'.repeat(50)));
    console.log(chalk.gray('Available workflows: fast-track, standard, full-morph, design-impl, ui-refresh'));
    console.log('');

  } catch (error) {
    console.log(chalk.red('\n✗ Workflow detection failed:'));
    console.log(chalk.red(error.message));
    if (options.verbose) {
      console.log(chalk.gray('\nStack trace:'));
      console.log(chalk.gray(error.stack));
    }
    console.log('');
    process.exit(1);
  }
}

/**
 * Get skip reason for a phase
 * @param {string} phase - Phase name
 * @param {Object} workflowConfig - Workflow config
 * @returns {string} Skip reason
 */
function getSkipReason(phase, workflowConfig) {
  const reasons = {
    'setup': 'context already loaded',
    'uiux': 'no significant UI changes',
    'clarify': 'spec is clear for this type',
    'sync': 'tactical decisions, not strategic',
    'proposal': 'combined into quick-analysis',
    'design': 'design not needed for visual-only changes',
    'tasks': 'simple enough for direct implementation'
  };

  return reasons[phase] || '';
}
