/**
 * MCP CLI command — MCP server analysis and optimization
 *
 * Usage:
 *   morph-spec mcp optimize
 *   morph-spec mcp list
 */

import chalk from 'chalk';
import { analyzeMCP } from '../../lib/context/mcp-optimizer.js';

const STATUS_COLORS = {
  used: chalk.green,
  unused: chalk.red,
  unknown: chalk.gray
};

function formatTokens(n) {
  return n >= 1000 ? `${(n / 1000).toFixed(1)}K` : String(n);
}

export async function mcpOptimizeCommand(options) {
  try {
    const analysis = analyzeMCP();

    if (!analysis.found) {
      console.log(chalk.yellow(`\n  ⚠ ${analysis.message}\n`));
      return;
    }

    console.log(chalk.cyan('\n  MCP Optimization Analysis\n'));
    console.log('  ' + '─'.repeat(60));

    console.log(`\n  Settings file: ${chalk.gray(analysis.settingsPath)}`);
    console.log(`  Total servers: ${analysis.totalServers}`);
    console.log(`  Total context overhead: ${chalk.yellow(formatTokens(analysis.totalOverhead) + ' tokens')}`);

    if (analysis.unusedCount > 0) {
      console.log(`  Unused servers: ${chalk.red(analysis.unusedCount)}`);
      console.log(`  Potential savings: ${chalk.green(formatTokens(analysis.potentialSavings) + ' tokens')}`);
    }

    if (analysis.recommendations.length === 0) {
      console.log(chalk.green('\n  ✓ MCP configuration looks optimized!\n'));
      return;
    }

    console.log(chalk.yellow('\n  Recommendations:\n'));
    for (const rec of analysis.recommendations) {
      console.log(`  ${chalk.bold(rec.title)}`);
      console.log(`  ${rec.description}`);
      console.log(`  Savings: ${chalk.green(formatTokens(rec.estimatedSavings) + ' tokens')}`);
      console.log(`  Action: ${chalk.cyan(rec.action)}`);
      console.log('');
    }

    console.log('  ' + '─'.repeat(60));
    console.log('');
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}

export async function mcpListCommand(options) {
  try {
    const analysis = analyzeMCP();

    if (!analysis.found) {
      console.log(chalk.yellow(`\n  ⚠ ${analysis.message}\n`));
      return;
    }

    if (analysis.servers.length === 0) {
      console.log(chalk.gray('\n  No MCP servers configured.\n'));
      return;
    }

    console.log(chalk.cyan('\n  Configured MCP Servers\n'));
    console.log('  ' + 'Name'.padEnd(25) + ' ' + 'Status'.padEnd(10) + ' ' + 'Overhead');
    console.log('  ' + '─'.repeat(50));

    for (const server of analysis.servers) {
      const colorFn = STATUS_COLORS[server.usageStatus] || chalk.white;
      console.log(
        '  ' +
        server.name.padEnd(25) + ' ' +
        colorFn(server.usageStatus.padEnd(10)) + ' ' +
        formatTokens(server.overhead) + ' tokens'
      );
    }

    console.log('\n  ' + `Total overhead: ${formatTokens(analysis.totalOverhead)} tokens`);
    if (analysis.recommendations.length > 0) {
      console.log(chalk.yellow(`  Run 'morph-spec mcp optimize' for recommendations`));
    }
    console.log('');
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}
