import { Command } from 'commander';
import chalk from 'chalk';
import { spawn } from 'child_process';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import { getApiKey, getApiUrl } from '../utils/config.js';
import { RIGSTATE_MCP_PACKAGE } from '../utils/versions.js';

// ESM compatibility for __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export function createMcpCommand() {
    const mcp = new Command('mcp');

    mcp
        .command('remote')
        .description('Show how to connect your editor to the hosted Rigstate MCP server (no local process)')
        .option('--show-key', 'Print the full API key instead of a placeholder')
        .action((opts: { showKey?: boolean }) => {
            let apiUrl = 'https://app.rigstate.com';
            let key = '<your sk_rigstate_ key>';
            try {
                apiUrl = getApiUrl().replace(/\/+$/, '');
                const k = getApiKey();
                if (k && opts.showKey) key = k;
                else if (k) key = `${k.slice(0, 16)}… (run with --show-key to print it)`;
            } catch { /* not logged in */ }
            const url = `${apiUrl}/api/mcp`;
            const shown = opts.showKey ? key : '$RIGSTATE_API_KEY';

            console.log(chalk.bold('\n🌐 Rigstate MCP over HTTP'));
            console.log(chalk.dim(`   Endpoint: ${url}`));
            console.log(chalk.dim('   Sign-in:  OAuth in the browser (recommended), or an API key header\n'));
            console.log(chalk.bold('Claude Code'));
            console.log(`   claude mcp add --transport http rigstate ${url}`);
            console.log(chalk.dim('   then run /mcp in Claude Code and choose Authenticate\n'));
            console.log(chalk.bold('Cursor / VS Code / Windsurf (mcp.json)'));
            console.log(JSON.stringify({ mcpServers: { rigstate: { url } } }, null, 2)
                .split('\n').map(l => `   ${l}`).join('\n'));
            console.log(chalk.bold('\nCodex (~/.codex/config.toml)'));
            console.log(`   [mcp_servers.rigstate]\n   url = "${url}"`);
            console.log(chalk.dim('   then: codex mcp login rigstate\n'));
            console.log(chalk.bold('With an API key instead (CI, headless)'));
            console.log(chalk.dim(`   API key:  ${key}`));
            console.log(`   claude mcp add --transport http rigstate ${url} --header "Authorization: Bearer ${shown}"`);
            console.log(`   mcp.json: "headers": { "Authorization": "Bearer ${shown}" }`);
            console.log(`   Codex:    bearer_token_env_var = "RIGSTATE_API_KEY"\n`);
            console.log(chalk.dim('Same tools as the local server; nothing runs on your machine.'));
        });

    mcp
        .description('Run the Rigstate MCP server for AI editors')
        .action(async () => {
            // Determine the path to the MCP server
            const possiblePaths = [
                // From packages/cli -> packages/mcp (sibling package)
                path.resolve(__dirname, '../../mcp/dist/index.js'),
                // If installed globally or via npm
                path.resolve(__dirname, '../../../mcp/dist/index.js'),
                // Development path from packages/cli/dist
                path.resolve(__dirname, '../../../packages/mcp/dist/index.js'),
            ];

            let serverPath = '';
            for (const p of possiblePaths) {
                if (fs.existsSync(p)) {
                    serverPath = p;
                    break;
                }
            }

            if (!serverPath) {
                console.error(chalk.red('❌ Error: Rigstate MCP Server binary not found.'));
                console.error(chalk.yellow('Please ensure that the mcp package is built:'));
                console.error(chalk.white('   cd packages/mcp && npm run build'));
                console.error('');
                console.error(chalk.dim('Or run directly with:'));
                console.error(chalk.white(`   npx ${RIGSTATE_MCP_PACKAGE}`));
                process.exit(1);
            }

            console.log(chalk.dim(`Starting MCP server from: ${serverPath}`));

            // SMART INJECTION: Inject global config into MCP environment
            const env = { ...process.env };

            try {
                const apiKey = getApiKey();
                if (apiKey) {
                    env.RIGSTATE_API_KEY = apiKey;
                    // Also inject the URL for consistency
                    env.RIGSTATE_APP_URL = getApiUrl();
                    env.RIGSTATE_API_URL = getApiUrl();
                }
            } catch (e) {
                // If not logged in, we carry on and let the MCP server show the final error
            }

            // Map VIBE_API_KEY if needed
            if (env.VIBE_API_KEY && !env.RIGSTATE_API_KEY) {
                env.RIGSTATE_API_KEY = env.VIBE_API_KEY;
            }

            // Spawn the MCP server as a child process
            const worker = spawn('node', [serverPath], {
                env,
                stdio: ['inherit', 'inherit', 'inherit']
            });

            worker.on('error', (err) => {
                console.error(chalk.red(`❌ Failed to start MCP server: ${err.message}`));
                process.exit(1);
            });

            worker.on('exit', (code) => {
                if (code !== 0 && code !== null) {
                    process.exit(code);
                }
            });
        });

    return mcp;
}
