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

/**
 * Search Patterns Command - Find relevant patterns
 *
 * Searches patterns-learned.md for keywords
 */

const program = new Command();

program
  .name('search-patterns')
  .description('Search for patterns by keyword')
  .argument('<keyword>', 'Keyword to search for')
  .option('--category <category>', 'Filter by category')
  .option('--limit <number>', 'Limit number of results', '10')
  .option('--json', 'Output as JSON', false)
  .action(async (keyword, options) => {
    try {
      // 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('No patterns learned yet. Complete some features first!\n'));
        process.exit(1);
      }

      // Read patterns file
      const content = readFileSync(patternsPath, 'utf8');

      // Split into pattern sections
      const sections = content.split('---').filter(s => s.trim().length > 0);

      // Search patterns
      const keywordLower = keyword.toLowerCase();
      const matches = [];

      sections.forEach(section => {
        if (section.toLowerCase().includes(keywordLower)) {
          // Extract pattern name
          const nameMatch = section.match(/## Pattern: (.+)/);
          const categoryMatch = section.match(/\*\*Category:\*\* (.+)/);
          const sourceMatch = section.match(/\*\*Source:\*\* (.+)/);

          if (nameMatch) {
            const patternName = nameMatch[1].trim();
            const category = categoryMatch ? categoryMatch[1].trim() : 'Unknown';
            const source = sourceMatch ? sourceMatch[1].trim() : 'Unknown';

            // Filter by category if specified
            if (options.category && !category.toLowerCase().includes(options.category.toLowerCase())) {
              return;
            }

            matches.push({
              name: patternName,
              category,
              source,
              content: section.trim(),
              preview: section.substring(0, 300).trim() + '...'
            });
          }
        }
      });

      // Limit results
      const limit = parseInt(options.limit, 10);
      const limitedMatches = matches.slice(0, limit);

      if (options.json) {
        // JSON output
        console.log(JSON.stringify({ keyword, matches: limitedMatches, total: matches.length }, null, 2));
        return;
      }

      // Pretty output
      if (limitedMatches.length === 0) {
        console.log(chalk.yellow(`\n⚠️  No patterns found for keyword: "${keyword}"\n`));
        console.log(chalk.gray('Try a different keyword or broader search term.\n'));
        return;
      }

      console.log(chalk.bold(`\n🔍 Found ${matches.length} pattern(s) for: "${keyword}"`));
      if (matches.length > limit) {
        console.log(chalk.gray(`Showing first ${limit} results (use --limit to see more)\n`));
      }
      console.log('━'.repeat(60));

      limitedMatches.forEach((match, index) => {
        console.log(chalk.green(`\n${index + 1}. ${match.name}`));
        console.log(chalk.cyan(`   Category: ${match.category}`));
        console.log(chalk.gray(`   Source: ${match.source}`));

        // Show first few lines of the pattern
        const lines = match.content.split('\n').slice(0, 15);
        console.log(chalk.gray('\n   ' + lines.join('\n   ')));

        if (match.content.split('\n').length > 15) {
          console.log(chalk.gray(`   ... (see full pattern in ${patternsPath})`));
        }
      });

      console.log('\n' + '━'.repeat(60));
      console.log(chalk.bold('\n💡 Usage:'));
      console.log(chalk.gray(`   Edit ${patternsPath} to see full pattern details\n`));

    } catch (error) {
      console.error(chalk.red(`\n❌ Error searching patterns: ${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;
