#!/usr/bin/env node

/**
 * MORPH-SPEC Agent Detection CLI
 *
 * Detecta automaticamente quais agentes devem ser ativados baseado
 * em keywords no input do usuário.
 *
 * Uso:
 *   node bin/detect-agents.js "implementar jobs agendados"
 *   node bin/detect-agents.js --verbose "criar dashboard com charts"
 *   node bin/detect-agents.js --json "adicionar background tasks"
 */

import { readFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const AGENTS_CONFIG_PATH = join(__dirname, '../content/.morph/config/agents.json');

// Cores para output no terminal
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  cyan: '\x1b[36m',
  gray: '\x1b[90m'
};

function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

/**
 * Carrega configuração de agentes
 * @returns {Object} Configuração de agentes
 */
function loadAgentsConfig() {
  try {
    const content = readFileSync(AGENTS_CONFIG_PATH, 'utf8');
    return JSON.parse(content);
  } catch (err) {
    console.error(`ERROR: Failed to load agents config: ${err.message}`);
    process.exit(1);
  }
}

/**
 * Detecta agentes baseado em user input
 * @param {string} userInput - Input do usuário
 * @param {Object} config - Configuração de agentes
 * @returns {Object} Resultado da detecção { core, specialists, all, matches }
 */
function detectAgents(userInput, config) {
  const input = userInput.toLowerCase();
  const coreAgents = config.agents.core || [];
  const specialists = config.agents.specialists || [];

  // Core agents sempre ativos
  const coreIds = coreAgents.map(a => a.id);

  // Detectar specialists por keyword matching
  const specialistMatches = [];

  for (const agent of specialists) {
    const keywords = agent.autoActivation?.keywords || [];
    const matchedKeywords = [];

    for (const keyword of keywords) {
      if (input.includes(keyword.toLowerCase())) {
        matchedKeywords.push(keyword);
      }
    }

    if (matchedKeywords.length > 0) {
      specialistMatches.push({
        id: agent.id,
        name: agent.name,
        emoji: agent.emoji,
        matchedKeywords: matchedKeywords,
        matchCount: matchedKeywords.length
      });
    }
  }

  // Ordenar por número de matches (mais relevante primeiro)
  specialistMatches.sort((a, b) => b.matchCount - a.matchCount);

  const specialistIds = specialistMatches.map(m => m.id);
  const allIds = [...new Set([...coreIds, ...specialistIds])];

  return {
    core: coreIds,
    specialists: specialistIds,
    all: allIds,
    matches: specialistMatches,
    input: userInput
  };
}

/**
 * Formata output em modo verbose
 * @param {Object} result - Resultado da detecção
 */
function formatVerbose(result) {
  log('\n╔════════════════════════════════════════════════════════════════╗', 'cyan');
  log('║                    AGENT DETECTION RESULT                      ║', 'cyan');
  log('╠════════════════════════════════════════════════════════════════╣', 'cyan');
  log(`║ Input: ${result.input.substring(0, 54).padEnd(54)} ║`, 'bright');
  log('╠════════════════════════════════════════════════════════════════╣', 'cyan');
  log('║ CORE AGENTS (always active)                                    ║', 'cyan');
  log('╠════════════════════════════════════════════════════════════════╣', 'cyan');

  result.core.forEach(id => {
    log(`║   ✓ ${id.padEnd(58)}║`, 'green');
  });

  if (result.specialists.length > 0) {
    log('╠════════════════════════════════════════════════════════════════╣', 'cyan');
    log('║ SPECIALIST AGENTS (keyword matched)                            ║', 'cyan');
    log('╠════════════════════════════════════════════════════════════════╣', 'cyan');

    result.matches.forEach(match => {
      const line = `${match.emoji} ${match.name} (${match.matchCount} matches)`;
      log(`║   ${line.padEnd(61)}║`, 'yellow');
      const keywords = match.matchedKeywords.join(', ');
      const keywordLine = `Keywords: ${keywords}`;
      // Quebrar em múltiplas linhas se necessário
      if (keywordLine.length > 58) {
        const chunks = keywordLine.match(/.{1,58}/g) || [];
        chunks.forEach((chunk, i) => {
          log(`║     ${chunk.padEnd(59)}║`, 'gray');
        });
      } else {
        log(`║     ${keywordLine.padEnd(59)}║`, 'gray');
      }
    });
  } else {
    log('╠════════════════════════════════════════════════════════════════╣', 'cyan');
    log('║ No specialist agents matched                                   ║', 'gray');
  }

  log('╠════════════════════════════════════════════════════════════════╣', 'cyan');
  log(`║ TOTAL: ${result.all.length} agents activated                                      ║`, 'bright');
  log('╚════════════════════════════════════════════════════════════════╝\n', 'cyan');
}

/**
 * Formata output em modo simples (apenas IDs)
 * @param {Object} result - Resultado da detecção
 */
function formatSimple(result) {
  result.all.forEach(id => console.log(id));
}

/**
 * Formata output em modo JSON
 * @param {Object} result - Resultado da detecção
 */
function formatJSON(result) {
  console.log(JSON.stringify(result, null, 2));
}

// ============================================================================
// MAIN
// ============================================================================

function main() {
  const args = process.argv.slice(2);

  // Parse flags
  const hasVerbose = args.includes('--verbose') || args.includes('-v');
  const hasJSON = args.includes('--json') || args.includes('-j');
  const hasHelp = args.includes('--help') || args.includes('-h');
  const hasIdsOnly = args.includes('--ids-only') || args.includes('-i');

  // Remove flags para pegar user input
  const userInput = args
    .filter(arg => !arg.startsWith('--') && !arg.startsWith('-'))
    .join(' ');

  if (hasHelp || args.length === 0) {
    log('\nMORPH-SPEC Agent Detection CLI', 'bright');
    log('\nUsage:', 'cyan');
    log('  node bin/detect-agents.js [options] "<user input>"', 'gray');
    log('\nOptions:', 'cyan');
    log('  -v, --verbose     Show detailed detection results', 'gray');
    log('  -j, --json        Output full result as JSON', 'gray');
    log('  -i, --ids-only    Output only agent IDs (one per line)', 'gray');
    log('  -h, --help        Show this help', 'gray');
    log('\nExamples:', 'cyan');
    log('  node bin/detect-agents.js "criar dashboard com charts"', 'gray');
    log('  node bin/detect-agents.js --verbose "implementar jobs agendados"', 'gray');
    log('  node bin/detect-agents.js --json "adicionar RAG pipeline"', 'gray');
    log('  node bin/detect-agents.js --ids-only "background tasks"\n', 'gray');
    process.exit(0);
  }

  if (!userInput) {
    console.error('ERROR: User input is required');
    console.error('Run with --help for usage information');
    process.exit(1);
  }

  // Carregar config e detectar agentes
  const config = loadAgentsConfig();
  const result = detectAgents(userInput, config);

  // Formatar output
  if (hasJSON) {
    formatJSON(result);
  } else if (hasVerbose) {
    formatVerbose(result);
  } else if (hasIdsOnly) {
    formatSimple(result);
  } else {
    // Default: JSON compact (só all array)
    console.log(JSON.stringify(result.all));
  }
}

main();
