#!/usr/bin/env node
import { execSync } from 'child_process';
import { existsSync, writeFileSync, mkdirSync, readFileSync } from 'fs';
import { join } from 'path';
import chalk from 'chalk';
import * as readline from 'readline';
async function promptYn(message) {
    const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
    return new Promise((resolve) => {
        rl.question(message, (answer) => {
            rl.close();
            resolve(answer.toLowerCase().startsWith('y'));
        });
    });
}
export async function setupMcpRouter(options = {}) {
    console.log(chalk.cyan('\n🔧 Setting up MCP Router for all harnesses...\n'));
    const homeDir = process.env.HOME || process.env.USERPROFILE || '~';
    const platforms = [
        { name: 'Claude Code', path: join(homeDir, '.claude'), type: 'claude' },
        { name: 'Factory.AI', path: join(homeDir, '.factory'), type: 'factory' },
        { name: 'VSCode', path: join(homeDir, '.vscode', 'mcp.json'), type: 'vscode' },
        { name: 'Cursor', path: join(homeDir, '.cursor', 'settings.json'), type: 'cursor' },
    ];
    let configured = 0;
    const results = [];
    // Step 1: Check UAP CLI availability
    console.log(chalk.bold('Step 1/5: Checking MCP Router installation...'));
    try {
        execSync('which uap', { stdio: 'pipe' });
        console.log(chalk.green('  ✓ UAP CLI found in PATH'));
    }
    catch {
        console.log(chalk.yellow('  ⚠ UAP CLI not in PATH, will use npx'));
    }
    // Step 2: Configure each platform
    for (const platform of platforms) {
        results.push({ platform: platform.name, status: 'checking' });
        if (!existsSync(platform.path)) {
            if (platform.type === 'vscode') {
                console.log(chalk.yellow(`  ⚠ ${platform.name} config not found at ${platform.path}`));
                results[results.length - 1].status = 'skipped';
                results[results.length - 1].message = 'Config file not found';
                continue;
            }
            console.log(chalk.cyan(`  Creating ${platform.name} config directory...`));
            try {
                mkdirSync(platform.path, { recursive: true });
            }
            catch (err) {
                console.log(chalk.yellow(`  ⚠ Could not create ${platform.name} config directory`));
                results[results.length - 1].status = 'failed';
                results[results.length - 1].message = 'Could not create directory';
                continue;
            }
        }
        // Determine MCP config path for platform
        let mcpConfigPath = '';
        if (platform.type === 'claude') {
            mcpConfigPath = join(platform.path, 'settings.json');
        }
        else if (platform.type === 'factory') {
            mcpConfigPath = join(platform.path, 'mcp.json');
        }
        else if (platform.type === 'vscode') {
            mcpConfigPath = platform.path;
        }
        else if (platform.type === 'cursor') {
            mcpConfigPath = platform.path;
        }
        if (!existsSync(mcpConfigPath)) {
            console.log(chalk.cyan(`  Creating ${platform.name} MCP config...`));
            const defaultConfig = {
                mcpServers: {
                    router: {
                        command: 'npx',
                        args: ['uap', 'mcp-router', 'start'],
                        description: 'Unified MCP Router - routes all tool calls',
                    },
                },
                metadata: {
                    version: '7.0.2',
                    autoGenerated: true,
                    replaces: 'individual MCP servers',
                },
            };
            try {
                writeFileSync(mcpConfigPath, JSON.stringify(defaultConfig, null, 2), 'utf8');
                console.log(chalk.green(`  ✓ ${platform.name} MCP config created with Router`));
                configured++;
            }
            catch (err) {
                console.log(chalk.yellow(`  ⚠ Could not create ${platform.name} MCP config`));
            }
        }
        else {
            try {
                const existingConfig = JSON.parse(readFileSync(mcpConfigPath, 'utf8'));
                if (existingConfig.mcpServers?.router) {
                    console.log(chalk.green(`  ✓ ${platform.name} already uses MCP Router`));
                    configured++;
                }
                else {
                    if (!options.force &&
                        !promptYn(`Replace ${platform.name} MCP servers with Router? (y/n)`)) {
                        console.log(chalk.yellow(`  ⚠ Skipped ${platform.name} migration`));
                        results[results.length - 1].status = 'skipped';
                        continue;
                    }
                    const migratedConfig = {
                        mcpServers: {
                            router: existingConfig.mcpServers || {
                                router: {
                                    command: 'npx',
                                    args: ['uap', 'mcp-router', 'start'],
                                },
                            },
                        },
                        _backup_original: existingConfig.mcpServers,
                        metadata: {
                            migrated: new Date().toISOString(),
                            version: '7.0.2',
                        },
                    };
                    writeFileSync(mcpConfigPath, JSON.stringify(migratedConfig, null, 2));
                    console.log(chalk.green(`  ✓ ${platform.name} migrated to MCP Router`));
                    configured++;
                }
            }
            catch (err) {
                console.log(chalk.yellow(`  ⚠ Could not read ${platform.name} config`));
            }
        }
        results[results.length - 1].status = 'done';
    }
    // Summary
    console.log('\n' + chalk.bold('Setup Summary:'));
    console.log(chalk.gray('─'.repeat(50)));
    for (const result of results) {
        const icon = result.status === 'done'
            ? '✓'
            : result.status === 'skipped'
                ? '⊘'
                : result.status === 'failed'
                    ? '✗'
                    : '?';
        console.log(`${icon} ${result.platform}: ${result.status}${result.message ? ` - ${result.message}` : ''}`);
    }
    console.log(chalk.gray('─'.repeat(50)));
    console.log(`Configured: ${configured}/${platforms.length} platforms`);
    // Validation
    console.log('\n' + chalk.bold('Step 5/5: Validating MCP Router...'));
    try {
        execSync('uap mcp-router list', { stdio: 'pipe' });
        console.log(chalk.green('  ✓ MCP Router validation passed'));
    }
    catch (err) {
        console.log(chalk.yellow('  ⚠ MCP Router validation skipped (may need npm install)'));
    }
    console.log('\n' + chalk.cyan('✅ MCP Router setup complete!\n'));
    console.log(chalk.gray('To use the router, restart your AI client.\n'));
}
//# sourceMappingURL=setup-mcp-router.js.map