// ai-bootstrap mcp <subcommand>
//
// Subcommands:
//   list         — list all available MCPs in the catalog
//   installed    — list MCPs already configured via ai-bootstrap
//   credentials  — interactively fill credentials into ~/.ai-bootstrap.env
//   help         — print help
import chalk from 'chalk';
import { existsSync, readFileSync, writeFileSync, chmodSync } from 'node:fs';
import { join } from 'node:path';
import { input, password, checkbox } from '@inquirer/prompts';
import { HOME } from '../utils/paths.js';
import { MCP_CATALOG, getMcpEntry } from '../applier/mcp-catalog.js';
import { writeMcpConfig, listInstalledMcps } from '../applier/mcp-config.js';
const ENV_FILE = join(HOME, '.ai-bootstrap.env');
function printMcpHelp() {
    console.log(`
${chalk.bold('ai-bootstrap mcp')} — MCP server management

${chalk.bold('Subcommands:')}
  ${chalk.cyan('list')}                          List all available MCPs in the catalog
  ${chalk.cyan('add')}                           Interactive multi-select MCP server(s)
  ${chalk.cyan('add github notion slack')}        Add specific MCPs by ID
  ${chalk.cyan('installed')}                     List MCPs configured via ai-bootstrap
  ${chalk.cyan('credentials')}                   Interactively fill credentials into ~/.ai-bootstrap.env
`);
}
function listAll() {
    const byCategory = new Map();
    for (const entry of Object.values(MCP_CATALOG)) {
        const list = byCategory.get(entry.category) ?? [];
        list.push(entry);
        byCategory.set(entry.category, list);
    }
    console.log(chalk.bold(`\n${Object.keys(MCP_CATALOG).length} MCP servers available\n`));
    for (const [cat, entries] of byCategory) {
        console.log(chalk.bold.cyan(`  ${cat.toUpperCase()}`));
        for (const e of entries.sort((a, b) => a.id.localeCompare(b.id))) {
            const credIcon = e.credentialKeys.length > 0 ? chalk.yellow(' 🔑') : '';
            console.log(`    ${chalk.green(e.id.padEnd(20))} ${e.description}${credIcon}`);
        }
        console.log('');
    }
    console.log(chalk.dim('🔑 = needs credentials. Run: ai-bootstrap mcp credentials\n'));
}
function listInstalled() {
    const installed = listInstalledMcps();
    if (installed.length === 0) {
        console.log(chalk.dim('\nHələ heç bir MCP qurulmayıb. Run: ai-bootstrap\n'));
        return;
    }
    console.log(chalk.bold(`\n${installed.length} MCP installed via ai-bootstrap:\n`));
    for (const m of installed) {
        const credIcon = m.needs_credential ? chalk.yellow(' 🔑') : '';
        console.log(`  ${chalk.green(m.id.padEnd(20))} ${chalk.dim(m.configured_at)}${credIcon}`);
    }
    console.log('');
}
function loadEnvFile() {
    if (!existsSync(ENV_FILE))
        return {};
    const env = {};
    for (const line of readFileSync(ENV_FILE, 'utf-8').split('\n')) {
        const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
        if (m)
            env[m[1]] = m[2];
    }
    return env;
}
function saveEnvFile(env) {
    const lines = [
        '# ai-bootstrap MCP credentials',
        '# Generated by `ai-bootstrap mcp credentials`',
        '# Source this in your shell: source ~/.ai-bootstrap.env',
        '# Then Claude Code will pick up ${VAR_NAME} substitutions in ~/.claude.json mcpServers',
        '',
    ];
    for (const [key, value] of Object.entries(env).sort()) {
        lines.push(`${key}=${value}`);
    }
    writeFileSync(ENV_FILE, lines.join('\n') + '\n', 'utf-8');
    chmodSync(ENV_FILE, 0o600);
}
async function collectCredentials() {
    const installed = listInstalledMcps();
    const needCreds = installed.filter((m) => m.needs_credential);
    if (needCreds.length === 0) {
        console.log(chalk.dim('\nHeç bir MCP credential gözləmir.\n'));
        return;
    }
    console.log(chalk.bold(`\n${needCreds.length} MCP credential gözləyir.\n`));
    console.log(chalk.dim(`Credentials saxlanılacaq: ${ENV_FILE} (chmod 600)\n`));
    const env = loadEnvFile();
    for (const tracked of needCreds) {
        const catalog = getMcpEntry(tracked.id);
        if (!catalog)
            continue;
        console.log(chalk.bold(`\n${chalk.cyan(catalog.name)} (${catalog.id})`));
        if (catalog.credentialHelp) {
            console.log(chalk.dim(`  ${catalog.credentialHelp}`));
        }
        for (const key of catalog.credentialKeys) {
            const current = env[key];
            if (current) {
                console.log(chalk.dim(`  ${key} = ${current.slice(0, 6)}*** (already set, skipping)`));
                continue;
            }
            const isSecret = /TOKEN|KEY|SECRET|PASSWORD/i.test(key);
            const value = isSecret
                ? await password({ message: `  ${key}:`, mask: '•' })
                : await input({ message: `  ${key}:` });
            if (value && value.trim().length > 0) {
                env[key] = value.trim();
            }
        }
    }
    saveEnvFile(env);
    console.log(chalk.green(`\n✓ Credentials saxlanıldı: ${ENV_FILE}\n`));
    console.log(chalk.dim('Shell-də yüklə (qoy ~/.zshrc və ya ~/.bashrc-ə):'));
    console.log(chalk.cyan(`  set -a; source ${ENV_FILE}; set +a\n`));
}
async function addMcps(names) {
    let toInstall = names;
    // No args → interactive multi-select
    if (toInstall.length === 0) {
        const byCategory = new Map();
        for (const entry of Object.values(MCP_CATALOG)) {
            const list = byCategory.get(entry.category) ?? [];
            list.push(entry);
            byCategory.set(entry.category, list);
        }
        const choices = [];
        for (const [cat, entries] of byCategory) {
            choices.push({ name: chalk.bold(`── ${cat.toUpperCase()} ──`), value: `__cat_${cat}`, disabled: true });
            for (const e of entries.sort((a, b) => a.id.localeCompare(b.id))) {
                const credIcon = e.credentialKeys.length > 0 ? chalk.yellow(' 🔑') : '';
                choices.push({ name: `${e.id.padEnd(22)} ${chalk.dim(e.description)}${credIcon}`, value: e.id });
            }
        }
        toInstall = await checkbox({
            message: 'MCP server-(lər)i seç: (Space = seç, Enter = bitir, 🔑 = credential lazımdır)',
            choices,
            pageSize: 25,
            required: true,
        });
    }
    console.log(chalk.dim(`\n  Quraşdırılır: ${toInstall.join(', ')}\n`));
    const result = writeMcpConfig(toInstall);
    console.log(`  ${chalk.green('✓')} ${result.installed.length} yeni MCP konfiq edildi`);
    if (result.skipped.length > 0) {
        console.log(chalk.dim(`  ${result.skipped.length} artıq var: ${result.skipped.join(', ')}`));
    }
    if (result.missingFromCatalog.length > 0) {
        console.log(chalk.yellow(`  ⚠ Kataloqda yoxdur: ${result.missingFromCatalog.join(', ')}`));
    }
    if (result.credentialsRequired.length > 0) {
        console.log(chalk.dim(`\n  ${result.credentialsRequired.length} MCP credential gözləyir. İçin: ${chalk.cyan('ai-bootstrap mcp credentials')}`));
    }
    console.log('');
}
export async function runMcpCommand(args) {
    const sub = args[0];
    if (!sub || sub === 'help' || sub === '--help' || sub === '-h') {
        printMcpHelp();
        return;
    }
    if (sub === 'list') {
        listAll();
        return;
    }
    if (sub === 'installed') {
        listInstalled();
        return;
    }
    if (sub === 'add') {
        await addMcps(args.slice(1).filter((a) => !a.startsWith('--')));
        return;
    }
    if (sub === 'credentials' || sub === 'creds') {
        await collectCredentials();
        return;
    }
    console.error(chalk.red(`Unknown mcp subcommand: ${sub}`));
    printMcpHelp();
    process.exit(1);
}
//# sourceMappingURL=mcp.js.map