#!/usr/bin/env node
/**
 * OpenCode Agency CLI
 * Main entry point for the CLI Brain system
 */

const { Command } = require('commander');
const fs = require('fs');
const path = require('path');

const { IntentRouter } = require('./dist/router/intent-router.js');
const { WorkflowEngine } = require('./dist/workflows/workflow-engine.js');
const { ConfigManager } = require('./dist/config/config-manager.js');

const program = new Command();

program
  .name('opencode-agency')
  .description('CLI Brain - 181 specialized agents for building software')
  .version('1.0.0');

// Route a task to the best agent
program
  .command('route')
  .description('Route a task to the best agent')
  .argument('<prompt>', 'Task description')
  .option('-v, --verbose', 'Show detailed routing information')
  .action(async (prompt, options) => {
    const router = new IntentRouter();
    const result = router.route(prompt);

    console.log('\n🧠 Routing Result:\n');
    console.log(`   Primary Agent: ${result.primaryAgent}`);
    console.log(`   Confidence: ${result.confidence}%`);
    
    if (options.verbose) {
      console.log('\n   Reasoning:');
      result.reasoning.forEach(r => console.log(`     • ${r}`));
    }

    if (result.secondaryAgent) {
      console.log(`   Secondary Agent: ${result.secondaryAgent}`);
    }

    if (result.workflow) {
      console.log(`   Workflow: ${result.workflow}`);
    }

    if (result.needsClarification && result.clarificationQuestions) {
      console.log('\n   Clarification Needed:');
      result.clarificationQuestions.forEach((q, i) => {
        console.log(`   ${i + 1}. ${q}`);
      });
    }
  });

// List all agents
program
  .command('list')
  .description('List all available agents')
  .option('-d, --department <dept>', 'Filter by department')
  .option('-j, --json', 'Output as JSON')
  .action(async (options) => {
    const registryPath = path.join(process.cwd(), 'router', 'agent-registry.json');
    
    if (!fs.existsSync(registryPath)) {
      console.log('❌ Agent registry not found. Run: opencode-agency build-registry');
      process.exit(1);
    }

    const registry = JSON.parse(fs.readFileSync(registryPath, 'utf-8'));
    
    if (options.json) {
      console.log(JSON.stringify(registry, null, 2));
      return;
    }

    console.log(`\n🤖 Available Agents (${registry.totalAgents} total)\n`);

    const departments = options.department 
      ? { [options.department]: registry.departments[options.department] }
      : registry.departments;

    for (const [dept, agents] of Object.entries(departments)) {
      if (dept === 'root') continue;
      
      console.log(`\n📁 ${dept.toUpperCase()} (${agents.length})`);
      console.log('─'.repeat(50));
      
      for (const agent of agents) {
        const emoji = agent.emoji || '🤖';
        console.log(`  ${emoji} ${agent.id}`);
        console.log(`     ${agent.description.substring(0, 60)}${agent.description.length > 60 ? '...' : ''}`);
      }
    }
  });

// Find agents by keyword
program
  .command('find')
  .description('Find agents by keyword')
  .argument('<query>', 'Search query')
  .option('-l, --limit <n>', 'Limit results', '10')
  .action(async (query, options) => {
    const router = new IntentRouter();
    const suggestions = router.getSuggestions(query);
    const limit = parseInt(options.limit);

    console.log(`\n🔍 Results for "${query}"\n`);
    
    if (suggestions.length === 0) {
      console.log('   No matching agents found.');
      return;
    }

    suggestions.slice(0, limit).forEach((agent, i) => {
      console.log(`   ${i + 1}. ${agent}`);
    });

    if (suggestions.length > limit) {
      console.log(`   ... and ${suggestions.length - limit} more`);
    }
  });

// Run a workflow
program
  .command('run')
  .description('Run a predefined workflow')
  .argument('<workflow>', 'Workflow name (e.g., landing-page, saas-mvp)')
  .option('-n, --name <name>', 'Project name')
  .option('-s, --style <style>', 'Design style (for applicable workflows)')
  .action(async (workflowName, options) => {
    const engine = new WorkflowEngine();
    
    try {
      const context = {};
      if (options.name) context.projectName = options.name;
      if (options.style) context.style = options.style;

      console.log(`\n🚀 Starting workflow: ${workflowName}\n`);
      const workflow = await engine.runPredefinedWorkflow(workflowName, context);
      
      console.log('\n✅ Workflow completed successfully!');
      console.log(`   Workflow ID: ${workflow.id}`);
    } catch (error) {
      console.error('\n❌ Workflow failed:', error);
      process.exit(1);
    }
  });

// Show workflow status
program
  .command('status')
  .description('Show workflow status')
  .argument('<workflowId>', 'Workflow ID')
  .action(async (workflowId) => {
    const engine = new WorkflowEngine();
    const status = engine.getWorkflowStatus(workflowId);

    if (!status) {
      console.log(`❌ Workflow ${workflowId} not found`);
      process.exit(1);
    }

    console.log(`\n📊 Workflow Status: ${workflowId}\n`);
    console.log(`   Status: ${status.status}`);
    console.log(`   Progress: ${status.progress.completed}/${status.progress.total} steps`);
    
    console.log('\n   Steps:');
    status.steps.forEach(step => {
      const icon = step.status === 'completed' ? '✅' 
        : step.status === 'running' ? '⏳'
        : step.status === 'failed' ? '❌'
        : '⏸️';
      console.log(`     ${icon} ${step.agent} (${step.status})`);
    });
  });

// Build agent registry
program
  .command('build-registry')
  .description('Build agent registry from agent files')
  .action(async () => {
    const { buildRegistry, saveRegistry } = require('../dist/scripts/build-registry.js');
    
    try {
      const registry = buildRegistry();
      saveRegistry(registry);
      
      console.log(`\n✅ Registry built successfully!`);
      console.log(`   Total agents: ${registry.totalAgents}`);
      console.log(`   Departments: ${Object.keys(registry.departments).length - 1}`);
    } catch (error) {
      console.error(`\n❌ Failed to build registry:`, error);
      process.exit(1);
    }
  });

// Validate agents
program
  .command('validate')
  .description('Validate agent files')
  .option('-f, --fix', 'Auto-fix issues where possible')
  .action(async (options) => {
    const { validateAgents } = require('../dist/scripts/validate-agents.js');
    
    try {
      const results = await validateAgents(options.fix);
      
      console.log('\n📋 Validation Results\n');
      console.log(`   Total agents: ${results.total}`);
      console.log(`   Valid: ${results.valid.length}`);
      console.log(`   Invalid: ${results.invalid.length}`);
      
      if (results.invalid.length > 0) {
        console.log('\n   Issues:');
        results.invalid.forEach(issue => {
          console.log(`   ❌ ${issue.file}: ${issue.error}`);
        });
        process.exit(1);
      } else {
        console.log('\n✅ All agents are valid!');
      }
    } catch (error) {
      console.error(`\n❌ Validation failed:`, error);
      process.exit(1);
    }
  });

// Create new agent
program
  .command('create-agent')
  .description('Create a new agent from template')
  .argument('<name>', 'Agent name (e.g., my-custom-agent)')
  .option('-d, --department <dept>', 'Department', 'specialized')
  .option('-e, --emoji <emoji>', 'Agent emoji', '🤖')
  .option('-c, --color <color>', 'Agent color (hex)', '#3B82F6')
  .action(async (name, options) => {
    const { createAgentFromTemplate } = require('../dist/scripts/create-agent.js');
    
    try {
      const filePath = await createAgentFromTemplate({
        name,
        department: options.department,
        emoji: options.emoji,
        color: options.color
      });
      
      console.log(`\n✅ Agent created!`);
      console.log(`   File: ${filePath}`);
      console.log(`\n   Next steps:`);
      console.log(`   1. Edit the agent file to customize instructions`);
      console.log(`   2. Add keywords to router/keywords.json`);
      console.log(`   3. Run: opencode-agency build-registry`);
    } catch (error) {
      console.error(`\n❌ Failed to create agent:`, error);
      process.exit(1);
    }
  });

// User preferences
program
  .command('config')
  .description('Manage user preferences')
  .option('-g, --get <key>', 'Get a config value')
  .option('-s, --set <key=value>', 'Set a config value')
  .option('-l, --list', 'List all config values')
  .action(async (options) => {
    const config = ConfigManager.getInstance();
    const prefs = config.getPreferences();

    if (options.list) {
      console.log('\n⚙️  User Preferences\n');
      console.log(JSON.stringify(prefs, null, 2));
    } else if (options.get) {
      const value = prefs[options.get];
      console.log(value !== undefined ? value : 'Not set');
    } else if (options.set) {
      const parts = options.set.split('=');
      const key = parts[0];
      const value = parts.slice(1).join('=');
      config.updatePreference(key, value);
      console.log(`✅ Set ${key} = ${value}`);
    } else {
      console.log('Use --list, --get <key>, or --set <key=value>');
    }
  });

// Interactive mode (default)
program
  .command('interactive', { isDefault: true })
  .description('Interactive mode (default)')
  .action(async () => {
    console.log('\n🧠 Welcome to CLI Brain - OpenCode Agency');
    console.log('   181 agents ready to help you build amazing things!\n');
    console.log('   Quick commands:');
    console.log('     opencode-agency route "<task>"     - Route a task');
    console.log('     opencode-agency list              - List all agents');
    console.log('     opencode-agency find "<keyword>"  - Find agents');
    console.log('     opencode-agency run <workflow>    - Run a workflow\n');
    console.log('   Try: opencode-agency route "build a landing page"\n');
  });

program.parse();
