/**
 * Troubleshoot Command
 * Search for solutions to common problems
 *
 * Usage: morph-spec troubleshoot <keywords...>
 */

import { searchIndex, getCategories } from '../../lib/troubleshooting/troubleshoot-index.js';
import { searchGrep } from '../../lib/troubleshooting/troubleshoot-grep.js';
import chalk from 'chalk';

// Severity colors and icons
const SEVERITY_CONFIG = {
  critical: { color: chalk.red, icon: '🔴', label: 'CRITICAL' },
  high: { color: chalk.yellow, icon: '🟠', label: 'HIGH' },
  medium: { color: chalk.blue, icon: '🔵', label: 'MEDIUM' },
  low: { color: chalk.gray, icon: '⚪', label: 'LOW' }
};

/**
 * Format a single result for display
 * @param {Object} result - Result object
 * @param {boolean} verbose - Show full content
 * @returns {string} Formatted output
 */
function formatResult(result, verbose = false) {
  const severity = SEVERITY_CONFIG[result.severity] || SEVERITY_CONFIG.medium;
  const lines = [];

  lines.push(chalk.gray('━'.repeat(50)));
  lines.push('');
  lines.push(`${severity.icon} ${severity.color.bold(severity.label)}: ${chalk.white.bold(result.title)}`);
  lines.push('');

  // File and section
  lines.push(`${chalk.gray('📁 Arquivo:')} ${chalk.cyan(result.file)}`);
  if (result.section) {
    lines.push(`${chalk.gray('📂 Seção:')} ${result.section}`);
  }
  lines.push('');

  // Cause
  if (result.cause) {
    lines.push(`${chalk.red('💡 Causa:')}`);
    lines.push(`   ${result.cause}`);
    lines.push('');
  }

  // Solution
  if (result.solution) {
    lines.push(`${chalk.green('✅ Solução:')}`);
    lines.push(`   ${chalk.white(result.solution)}`);
    lines.push('');
  }

  // Content preview (for grep results or verbose mode)
  if (verbose && result.content) {
    lines.push(`${chalk.gray('📝 Conteúdo:')}`);
    const contentLines = result.content.split('\n').slice(0, 15);
    contentLines.forEach(line => {
      lines.push(`   ${chalk.gray(line)}`);
    });
    lines.push('');
  }

  // Keywords matched
  if (result.keywords && result.keywords.length > 0) {
    const keywords = Array.isArray(result.keywords)
      ? result.keywords.slice(0, 5).join(', ')
      : result.keywords;
    lines.push(`${chalk.gray('🏷️  Keywords:')} ${chalk.dim(keywords)}`);
  }

  // Source (index or grep)
  if (result.source === 'grep') {
    lines.push(`${chalk.gray('🔍 Fonte:')} ${chalk.dim('Busca em arquivos (grep)')}`);
  }

  lines.push('');

  return lines.join('\n');
}

/**
 * Format the summary footer
 * @param {Object} stats - Search statistics
 * @returns {string} Formatted summary
 */
function formatSummary(stats) {
  const lines = [];

  lines.push(chalk.gray('━'.repeat(50)));
  lines.push('');

  if (stats.total === 0) {
    lines.push(chalk.yellow('⚠️  Nenhum resultado encontrado no índice ou arquivos.'));
    lines.push('');
    lines.push(chalk.dim('💡 Dicas:'));
    lines.push(chalk.dim('   • Tente termos mais específicos (ex: "NU1605" em vez de "error")'));
    lines.push(chalk.dim('   • Use parte da mensagem de erro exata'));
    lines.push(chalk.dim('   • Consulte a documentação: morph-spec read frontend/blazor/pitfalls.md'));
  } else {
    lines.push(`${chalk.green('✅')} Encontrado ${chalk.bold(stats.total)} resultado(s)`);

    if (stats.fromIndex > 0) {
      lines.push(`   ${chalk.dim(`• ${stats.fromIndex} do índice de problemas conhecidos`)}`);
    }
    if (stats.fromGrep > 0) {
      lines.push(`   ${chalk.dim(`• ${stats.fromGrep} da busca em arquivos`)}`);
    }
  }

  lines.push('');

  return lines.join('\n');
}

/**
 * List all categories
 */
function listCategories() {
  const categories = getCategories();

  console.log('');
  console.log(chalk.bold('📂 Categorias disponíveis:'));
  console.log('');

  for (const [id, category] of Object.entries(categories)) {
    const name = typeof category === 'object' ? category.name : category;
    const desc = typeof category === 'object' ? category.description : '';
    console.log(`   ${chalk.cyan(id.padEnd(12))} ${name}`);
    if (desc) {
      console.log(`   ${' '.repeat(12)} ${chalk.dim(desc)}`);
    }
  }

  console.log('');
  console.log(chalk.dim('Uso: morph-spec troubleshoot --category efcore "sua busca"'));
  console.log('');
}

/**
 * Main troubleshoot command
 * @param {string[]} keywords - Search keywords
 * @param {Object} options - Command options
 */
export async function troubleshootCommand(keywords, options = {}) {
  // Handle --list-categories flag
  if (options.listCategories) {
    listCategories();
    return;
  }

  // Validate keywords
  if (!keywords || keywords.length === 0) {
    console.log('');
    console.log(chalk.yellow('⚠️  Por favor, forneça termos de busca.'));
    console.log('');
    console.log(chalk.dim('Exemplos:'));
    console.log(chalk.dim('   morph-spec troubleshoot "blazor.web.js 404"'));
    console.log(chalk.dim('   morph-spec troubleshoot DbContext concurrent'));
    console.log(chalk.dim('   morph-spec troubleshoot NU1605 Azure.Identity'));
    console.log('');
    console.log(chalk.dim('Opções:'));
    console.log(chalk.dim('   --category <cat>    Filtrar por categoria (blazor, efcore, azure)'));
    console.log(chalk.dim('   --verbose, -v       Mostrar conteúdo completo'));
    console.log(chalk.dim('   --list-categories   Listar categorias disponíveis'));
    console.log('');
    return;
  }

  const searchTerms = Array.isArray(keywords) ? keywords : [keywords];

  console.log('');
  console.log(`${chalk.cyan('🔍')} Buscando soluções para: ${chalk.bold(`"${searchTerms.join(' ')}"`)}`);
  console.log('');

  // Search options
  const searchOptions = {};
  if (options.category) {
    searchOptions.category = options.category;
    console.log(chalk.dim(`   Filtrando por categoria: ${options.category}`));
    console.log('');
  }

  // Level 1: Search index
  let indexResults = searchIndex(searchTerms, searchOptions);
  indexResults = indexResults.map(r => ({ ...r, source: 'index' }));

  // Level 2: Grep fallback (if few results)
  let grepResults = [];
  if (indexResults.length < 3) {
    grepResults = searchGrep(searchTerms, searchOptions);
    // Filter out duplicates (same file + section)
    const indexKeys = new Set(indexResults.map(r => `${r.file}:${r.section}`));
    grepResults = grepResults.filter(r => !indexKeys.has(`${r.file}:${r.section}`));
  }

  // Combine and limit results
  const allResults = [...indexResults, ...grepResults].slice(0, 10);

  // Display results
  for (const result of allResults) {
    console.log(formatResult(result, options.verbose));
  }

  // Display summary
  console.log(formatSummary({
    total: allResults.length,
    fromIndex: indexResults.length,
    fromGrep: grepResults.slice(0, 10 - indexResults.length).length
  }));

  // Hint for web search (handled by Claude Code slash command)
  if (allResults.length === 0) {
    console.log(chalk.dim('💡 Use /morph-troubleshoot no Claude Code para busca web em'));
    console.log(chalk.dim('   GitHub Issues, Stack Overflow e Microsoft Learn.'));
    console.log('');
  }
}

export default troubleshootCommand;
