/**
 * olam mcp import — Discovery sweep + interactive multi-select picker.
 *
 * Scans 5 source paths in parallel, deduplicates by service name, presents
 * a numbered multi-select list, validates each picked entry (5s timeout),
 * then registers with mcp-auth-service.
 *
 * Idempotent re-run: skips already-registered services unless --reimport.
 */
import * as readline from 'node:readline';
import pc from 'picocolors';
import { printError, printInfo } from '../../output.js';
import { discoverMcpSources } from './import-discovery.js';
import { validateMcpEntry } from './import-validate.js';
import { getMcpAuthClient } from './client.js';
async function multiSelectPicker(entries) {
    if (entries.length === 0)
        return [];
    console.log('\n' + pc.bold('Discovered MCP servers:'));
    entries.forEach((e, i) => {
        console.log(`  ${pc.dim(`[${i + 1}]`)} ${pc.cyan(e.name.padEnd(20))} ${pc.dim(e.sourceLabel)}`);
    });
    console.log('\n' + pc.dim('Enter numbers to import (e.g. 1,2,3 or "all" or Enter to skip):'));
    const answer = await new Promise((resolve) => {
        const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
        rl.question('> ', (ans) => {
            rl.close();
            resolve(ans.trim());
        });
    });
    if (!answer || answer === '')
        return [];
    if (answer.toLowerCase() === 'all')
        return entries;
    const indices = answer
        .split(/[\s,]+/)
        .map((s) => parseInt(s, 10) - 1)
        .filter((i) => !isNaN(i) && i >= 0 && i < entries.length);
    const unique = [...new Set(indices)];
    return unique.map((i) => entries[i]).filter((e) => e != null);
}
export function registerMcpImport(cmd) {
    cmd
        .command('import')
        .description('Discover MCP servers from Claude Code, Desktop, Cursor, Windsurf, and .mcp.json')
        .option('--reimport', 'Re-import services that are already registered')
        .option('--no-validate', 'Skip validation probes')
        .option('--repo-paths <paths>', 'Comma-separated list of repo paths to scan for .mcp.json')
        .action(async (opts) => {
        const client = getMcpAuthClient();
        // Load existing services for idempotency check
        let existingIds = new Set();
        try {
            const data = await client.status();
            existingIds = new Set((data.mcps ?? []).map((m) => m.id));
        }
        catch { /* mcp-auth not running — treat all as new */ }
        printInfo('Scanning', 'Claude Code, Claude Desktop, Cursor, Windsurf, .mcp.json…');
        const repoPaths = opts.repoPaths ? opts.repoPaths.split(',').map((s) => s.trim()) : undefined;
        const { entries, sources, durationMs } = await discoverMcpSources(repoPaths);
        if (entries.length === 0) {
            console.log(pc.dim('No MCP servers found in any source path.'));
            return;
        }
        printInfo('Sources', sources.length > 0 ? sources.join(', ') : 'none');
        printInfo('Found', `${entries.length} MCP server(s) in ${Math.round(durationMs)}ms`);
        // Filter already-registered unless --reimport
        let candidates = entries;
        let skippedCount = 0;
        if (!opts.reimport) {
            const filtered = entries.filter((e) => !existingIds.has(e.name));
            skippedCount = entries.length - filtered.length;
            candidates = filtered;
        }
        if (skippedCount > 0) {
            console.log(pc.dim(`skipped: ${skippedCount} already registered`));
        }
        if (candidates.length === 0) {
            console.log(pc.dim('Nothing new to import. Use --reimport to force.'));
            return;
        }
        // Interactive picker
        const selected = await multiSelectPicker(candidates);
        if (selected.length === 0) {
            console.log(pc.dim('No servers selected.'));
            return;
        }
        console.log(`\nImporting ${selected.length} server(s)…`);
        let importedCount = 0;
        let validatedCount = 0;
        for (const entry of selected) {
            let validated = false;
            let validationReason = 'skipped';
            if (opts.validate !== false) {
                process.stdout.write(`  ${pc.dim('→')} ${entry.name}  validating… `);
                const vr = await validateMcpEntry(entry);
                validated = vr.validated;
                validationReason = vr.reason;
                process.stdout.write(validated ? pc.green('ok\n') : pc.yellow(`unvalidated (${vr.reason})\n`));
            }
            else {
                console.log(`  ${pc.dim('→')} ${entry.name}  ${pc.dim('(validation skipped)')}`);
            }
            if (validated)
                validatedCount++;
            // Register as static-key (type depends on whether command uses env vars for tokens)
            const result = await client.staticAdd({
                service: entry.name,
                token: `mcp://${entry.command}`,
                label: entry.name,
            });
            if (result.ok) {
                importedCount++;
            }
            else {
                printError(`Failed to register ${entry.name}: ${result.error ?? 'unknown error'}`);
            }
        }
        console.log('');
        console.log(pc.green(`✓ Imported ${importedCount}/${selected.length}`));
        if (validatedCount > 0) {
            console.log(pc.dim(`  ${validatedCount} validated, ${importedCount - validatedCount} unvalidated`));
        }
    });
}
//# sourceMappingURL=import.js.map