import { Command } from 'commander';
import chalk from 'chalk';
import { appendFileSync, existsSync, readFileSync } from 'fs';
import { join } from 'path';

/**
 * Capture Pattern Command - Document lessons learned
 *
 * Appends patterns to patterns-learned.md for future reference
 */

const program = new Command();

const VALID_CATEGORIES = ['success', 'avoid', 'optimization', 'security', 'convention', 'best-practice'];

program
  .name('capture-pattern')
  .description('Capture a pattern or lesson learned from a feature')
  .argument('<feature>', 'Feature name')
  .argument('<category>', `Pattern category (${VALID_CATEGORIES.join(', ')})`)
  .argument('<description>', 'Brief description of the pattern')
  .option('--auto', 'Auto-capture without opening editor', false)
  .action(async (featureName, category, description, options) => {
    try {
      // Validate category
      if (!VALID_CATEGORIES.includes(category)) {
        console.error(chalk.red(`\n❌ Invalid category: ${category}`));
        console.log(chalk.gray(`Valid categories: ${VALID_CATEGORIES.join(', ')}\n`));
        process.exit(1);
      }

      // Get patterns file path
      const patternsPath = join(process.cwd(), '.morph/memory/patterns-learned.md');

      if (!existsSync(patternsPath)) {
        console.error(chalk.red(`\n❌ Patterns file not found: ${patternsPath}`));
        console.log(chalk.yellow('Run "morph-spec init" to create the file.\n'));
        process.exit(1);
      }

      // Create pattern entry
      const timestamp = new Date().toISOString().split('T')[0];
      const categoryDisplay = category === 'avoid' ? 'Anti-Pattern to Avoid' :
                              category === 'success' ? 'Best Practice' :
                              category === 'optimization' ? 'Performance Optimization' :
                              category === 'security' ? 'Security Best Practice' :
                              category === 'convention' ? 'Convention' :
                              'Best Practice';

      const patternTemplate = `

---

## Pattern: ${description}

**Source:** Feature \`${featureName}\` (${timestamp})
**Category:** ${categoryDisplay}
**Date:** ${timestamp}

**Problem:**
[Describe the problem this pattern solves]

**Implementation:**
\`\`\`csharp
// Add code example here
\`\`\`

**Why:**
- [Reason 1]
- [Reason 2]

**When to Use:**
[Describe scenarios where this pattern applies]

**Reuse:** [List features/scenarios where this can be reused]

---
`;

      // Append to file
      appendFileSync(patternsPath, patternTemplate, 'utf8');

      console.log(chalk.green(`\n✅ Pattern captured successfully`));
      console.log(chalk.cyan(`   Feature: ${featureName}`));
      console.log(chalk.cyan(`   Category: ${categoryDisplay}`));
      console.log(chalk.cyan(`   Description: ${description}\n`));

      if (!options.auto) {
        console.log(chalk.bold('📝 Next Steps:'));
        console.log(chalk.gray(`1. Edit ${patternsPath}`));
        console.log(chalk.gray('2. Fill in: Problem, Implementation (code), Why, When to Use'));
        console.log(chalk.gray('3. Add code examples and rationale\n'));
      }

      // Show location in file
      const content = readFileSync(patternsPath, 'utf8');
      const lines = content.split('\n');
      const patternLine = lines.findIndex(line => line.includes(`Pattern: ${description}`));

      if (patternLine !== -1) {
        console.log(chalk.gray(`Pattern added at line ${patternLine + 1}`));
      }

      console.log(chalk.gray(`\nFile: ${patternsPath}\n`));

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

// 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;
