/**
 * MORPH-SPEC Session Summary Command
 *
 * Shows a comprehensive summary of the current session including:
 * - Phases completed
 * - Decisions taken
 * - Progress on tasks
 * - Next steps
 *
 * Usage:
 *   morph-spec session-summary <feature-name>
 *   morph-spec summary <feature-name>
 */

import fs from 'fs';
import path from 'path';
import chalk from 'chalk';
import { loadState, getFeature } from '../../core/state/state-manager.js';

// Phase order for display
const PHASE_ORDER = [
  { key: 'proposal', name: 'FASE 0: PROPOSAL', emoji: '📝' },
  { key: 'setup', name: 'FASE 1: SETUP', emoji: '⚙️' },
  { key: 'uiux', name: 'FASE 1.5: UI/UX', emoji: '🎨', optional: true },
  { key: 'design', name: 'FASE 2: DESIGN', emoji: '📐' },
  { key: 'clarify', name: 'FASE 3: CLARIFY', emoji: '❓' },
  { key: 'tasks', name: 'FASE 4: TASKS', emoji: '📋' },
  { key: 'implement', name: 'FASE 5: IMPLEMENT', emoji: '🔨' },
  { key: 'sync', name: 'FASE 6: SYNC', emoji: '🔄', optional: true }
];

/**
 * Get phase index for comparison
 */
function getPhaseIndex(phaseKey) {
  return PHASE_ORDER.findIndex(p => p.key === phaseKey);
}

/**
 * Read decisions from decisions.md
 */
function readDecisions(featurePath) {
  const decisionsPath = path.join(featurePath, 'decisions.md');
  if (!fs.existsSync(decisionsPath)) return [];

  try {
    const content = fs.readFileSync(decisionsPath, 'utf-8');
    const decisions = [];

    // Parse ADR sections
    const adrMatches = content.matchAll(/##\s+ADR[- ]?\d*:?\s*(.+?)(?=\n##|\n$|$)/gis);
    for (const match of adrMatches) {
      const title = match[1].split('\n')[0].trim();
      decisions.push(title);
    }

    // Also parse simple decisions format
    const simpleMatches = content.matchAll(/[-*]\s+\*\*(.+?)\*\*:\s*(.+)/g);
    for (const match of simpleMatches) {
      decisions.push(`${match[1]}: ${match[2]}`);
    }

    return decisions.slice(0, 10); // Limit to 10
  } catch {
    return [];
  }
}

/**
 * Check which outputs exist
 */
function checkOutputs(featurePath) {
  const outputs = [
    { file: 'proposal.md', name: 'Proposal' },
    { file: 'spec.md', name: 'Spec' },
    { file: 'contracts.cs', name: 'Contracts' },
    { file: 'ui-design-system.md', name: 'UI Design System' },
    { file: 'ui-mockups.md', name: 'UI Mockups' },
    { file: 'ui-components.md', name: 'UI Components' },
    { file: 'ui-flows.md', name: 'UI Flows' },
    { file: 'decisions.md', name: 'Decisions' },
    { file: 'recap.md', name: 'Recap' }
  ];

  return outputs.map(o => ({
    ...o,
    exists: fs.existsSync(path.join(featurePath, o.file))
  }));
}

/**
 * Generate progress bar
 */
function progressBar(completed, total, width = 30) {
  if (total === 0) return chalk.gray('[' + '░'.repeat(width) + '] 0%');

  const percentage = Math.round((completed / total) * 100);
  const filled = Math.round((completed / total) * width);
  const empty = width - filled;

  const bar = '█'.repeat(filled) + '░'.repeat(empty);
  const color = percentage === 100 ? chalk.green : percentage > 50 ? chalk.yellow : chalk.cyan;

  return color(`[${bar}] ${percentage}%`);
}

/**
 * Get next steps suggestions
 */
function getNextSteps(feature, currentPhaseIndex) {
  const steps = [];

  if (!feature) {
    steps.push('Run: morph-spec state set <feature> phase proposal');
    return steps;
  }

  const nextPhase = PHASE_ORDER[currentPhaseIndex + 1];

  if (feature.tasks?.total > 0 && feature.tasks?.completed < feature.tasks?.total) {
    steps.push(`Continue implementing tasks (${feature.tasks.completed}/${feature.tasks.total} done)`);
  }

  if (nextPhase) {
    steps.push(`Advance to ${nextPhase.name}`);
  }

  if (feature.phase === 'implement' && feature.tasks?.completed === feature.tasks?.total) {
    steps.push('Generate recap.md');
    steps.push('Consider running FASE 6: SYNC to promote decisions');
  }

  return steps;
}

/**
 * Main command handler
 */
export async function sessionSummaryCommand(featureName, options = {}) {
  const featurePath = path.join(process.cwd(), '.morph/project/outputs', featureName);

  // Header
  console.log(chalk.cyan('\n╔════════════════════════════════════════════════════════════╗'));
  console.log(chalk.cyan(`║  📊 SESSION SUMMARY: ${featureName.padEnd(35)}║`));
  console.log(chalk.cyan('╚════════════════════════════════════════════════════════════╝\n'));

  // Get feature from state
  let feature = null;
  try {
    feature = getFeature(featureName);
  } catch {
    // State may not exist
  }

  // JSON output mode
  if (options.json) {
    const outputs = checkOutputs(featurePath);
    const decisions = readDecisions(featurePath);
    const summary = {
      feature: featureName,
      status: feature?.status || 'unknown',
      phase: feature?.phase || 'unknown',
      workflow: feature?.workflow || 'auto',
      agents: feature?.activeAgents || [],
      tasks: feature?.tasks || { total: 0, completed: 0 },
      checkpoints: feature?.checkpoints || [],
      outputs: outputs.filter(o => o.exists).map(o => o.name),
      decisions,
      skippedPhases: feature?.skippedPhases || []
    };
    console.log(JSON.stringify(summary, null, 2));
    return;
  }

  // Check if feature directory exists
  if (!fs.existsSync(featurePath)) {
    console.log(chalk.yellow('  ⚠️  Feature directory not found'));
    console.log(chalk.gray(`     Expected: ${featurePath}\n`));

    if (feature) {
      console.log(chalk.gray('  State exists but no outputs directory.'));
      console.log(chalk.gray(`  Phase: ${feature.phase}`));
    }
    return;
  }

  // Current Status
  const currentPhaseIndex = feature ? getPhaseIndex(feature.phase) : -1;

  console.log(chalk.bold('📌 Current Status'));
  console.log(chalk.gray('─'.repeat(50)));
  console.log(`  Phase:    ${chalk.cyan(feature?.phase || 'unknown')}`);
  console.log(`  Status:   ${chalk.cyan(feature?.status || 'unknown')}`);
  console.log(`  Workflow: ${chalk.cyan(feature?.workflow || 'auto')}`);
  console.log('');

  // Phases Progress
  console.log(chalk.bold('🔄 Phases Progress'));
  console.log(chalk.gray('─'.repeat(50)));

  for (let i = 0; i < PHASE_ORDER.length; i++) {
    const phase = PHASE_ORDER[i];
    let status;
    let color;

    const isSkipped = feature?.skippedPhases?.includes(phase.key);

    if (isSkipped) {
      status = 'SKIP';
      color = chalk.gray;
    } else if (i < currentPhaseIndex) {
      status = '✓';
      color = chalk.green;
    } else if (i === currentPhaseIndex) {
      status = '▸';
      color = chalk.cyan;
    } else {
      status = ' ';
      color = chalk.gray;
    }

    const optionalTag = phase.optional ? chalk.gray(' (optional)') : '';
    console.log(`  ${color(status)} ${phase.emoji} ${color(phase.name)}${optionalTag}`);
  }
  console.log('');

  // Tasks Progress
  if (feature?.tasks && feature.tasks.total > 0) {
    console.log(chalk.bold('📋 Tasks Progress'));
    console.log(chalk.gray('─'.repeat(50)));
    console.log(`  ${progressBar(feature.tasks.completed, feature.tasks.total)}`);
    console.log(`  ${chalk.gray(`${feature.tasks.completed}/${feature.tasks.total} tasks completed`)}`);
    console.log('');
  }

  // Active Agents
  if (feature?.activeAgents && feature.activeAgents.length > 0) {
    console.log(chalk.bold('🤖 Active Agents'));
    console.log(chalk.gray('─'.repeat(50)));
    feature.activeAgents.forEach(agent => {
      console.log(`  • ${chalk.cyan(agent)}`);
    });
    console.log('');
  }

  // Outputs
  const outputs = checkOutputs(featurePath);
  const createdOutputs = outputs.filter(o => o.exists);

  if (createdOutputs.length > 0) {
    console.log(chalk.bold('📄 Outputs Created'));
    console.log(chalk.gray('─'.repeat(50)));
    createdOutputs.forEach(o => {
      console.log(`  ${chalk.green('✓')} ${o.name}`);
    });
    console.log('');
  }

  // Decisions Taken
  const decisions = readDecisions(featurePath);
  if (decisions.length > 0) {
    console.log(chalk.bold('🎯 Decisions Taken'));
    console.log(chalk.gray('─'.repeat(50)));
    decisions.forEach(d => {
      console.log(`  • ${chalk.white(d)}`);
    });
    console.log('');
  }

  // Checkpoints
  if (feature?.checkpoints && feature.checkpoints.length > 0) {
    console.log(chalk.bold('🏁 Checkpoints'));
    console.log(chalk.gray('─'.repeat(50)));
    feature.checkpoints.slice(-5).forEach(cp => {
      const date = new Date(cp.timestamp).toLocaleString();
      console.log(`  ${chalk.gray(date)} - ${cp.note}`);
    });
    console.log('');
  }

  // Next Steps
  const nextSteps = getNextSteps(feature, currentPhaseIndex);
  if (nextSteps.length > 0) {
    console.log(chalk.bold('➡️  Next Steps'));
    console.log(chalk.gray('─'.repeat(50)));
    nextSteps.forEach((step, i) => {
      console.log(`  ${i + 1}. ${chalk.yellow(step)}`);
    });
    console.log('');
  }
}
