"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerInitCommand = registerInitCommand;
const fs_1 = __importDefault(require("fs"));
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const index_js_1 = require("../../lib/db/index.js");
const shared_js_1 = require("../shared.js");
const ui_js_1 = require("../ui.js");
/**
 * Detect which reviewer CLIs (claude/codex/gemini/opencode/kimi) are
 * usable on the host. Returns the list of human-friendly names that
 * passed the full detect-and-verify probe. Used by `chorus init` to
 * warn when zero are installed — the cockpit would otherwise look
 * healthy but every run would hang on first dispatch.
 */
async function detectReviewerClis() {
    try {
        const { detectAllClis } = await import('../../lib/cli-detect.js');
        const all = detectAllClis();
        const labelMap = {
            'claude-code': 'claude',
            'codex-cli': 'codex',
            'gemini-cli': 'gemini',
            'opencode-cli': 'opencode',
            'kimi-cli': 'kimi',
            'grok-cli': 'grok',
            'antigravity-cli': 'agy',
        };
        return {
            clis: all.filter((d) => d.found).map((d) => labelMap[d.id] ?? d.id),
            detectFailed: false,
        };
    }
    catch (err) {
        return {
            clis: [],
            detectFailed: true,
            detectError: err instanceof Error ? err.message : String(err),
        };
    }
}
/**
 * Detect Claude Code / Codex / Gemini / OpenCode and wire each one.
 * If the user passed `--connect <list>` we only touch those.
 */
async function runOrchestratorAutoConnect(connectFlag) {
    const { autoConnectAll } = await import('../../daemon/orchestrators/index.js');
    const binPath = shared_js_1.CHORUS_BIN_PATH;
    const ALL_NAMES = [
        'claude',
        'codex',
        'gemini',
        'opencode',
        'kimi',
        'cursor',
        'windsurf',
    ];
    let only;
    if (connectFlag) {
        const wanted = connectFlag.split(',').map((s) => s.trim().toLowerCase());
        only = [];
        for (const w of wanted) {
            if (ALL_NAMES.includes(w)) {
                only.push(w);
            }
            else {
                console.error(`Unknown orchestrator '${w}' in --connect. Valid: ${ALL_NAMES.join(', ')}`);
                process.exit(1);
            }
        }
    }
    console.log('');
    console.log(`  ${ui_js_1.c.dim('Detecting orchestrators...')}`);
    const result = await autoConnectAll({ binPath, ...(only ? { only } : {}) });
    for (const step of result.steps) {
        if (!step.detected) {
            console.log(`  ${ui_js_1.c.gray('○')} ${ui_js_1.c.gray(step.label.padEnd(14))} ${ui_js_1.c.dim('not detected')}`);
            continue;
        }
        if (step.error) {
            console.log(`  ${ui_js_1.c.yellow('!')} ${ui_js_1.c.yellow(step.label.padEnd(14))} ${ui_js_1.c.dim(step.error)}`);
            continue;
        }
        const parts = [];
        if (step.registered)
            parts.push('MCP registered');
        else
            parts.push('MCP already registered');
        if (step.toolsAdded > 0)
            parts.push(`${step.toolsAdded} tool(s) approved`);
        else if (step.name === 'claude')
            parts.push('all tools approved');
        if (step.slashCommand === 'installed')
            parts.push('/chorus installed');
        else if (step.slashCommand === 'updated')
            parts.push('/chorus updated');
        console.log(`  ${ui_js_1.sym.ok} ${ui_js_1.c.bold(step.label.padEnd(14))} ${ui_js_1.c.dim(parts.join(' · '))}`);
    }
    if (!result.anyConnected) {
        console.log('');
        console.log(`  ${ui_js_1.sym.info} ${ui_js_1.c.dim('No supported editors found. Connect manually later with')} ${ui_js_1.c.bold('chorus connect')}`);
    }
}
function registerInitCommand(program) {
    program
        .command('init')
        .description('Initialize Chorus: create ~/.chorus/, seed database, register MCP with detected editors')
        .option('--no-register', 'Skip auto-detecting orchestrators')
        .option('--connect <list>', 'Comma-separated list of CLIs to connect (claude,codex,gemini,opencode,kimi,cursor,windsurf). Default: all detected.')
        .action(async (opts) => {
        try {
            const chorusDir = path_1.default.join(os_1.default.homedir(), '.chorus');
            console.log('');
            console.log((0, ui_js_1.header)(ui_js_1.sym.pointer, 'Initializing Chorus...'));
            console.log('');
            if (!fs_1.default.existsSync(chorusDir)) {
                fs_1.default.mkdirSync(chorusDir, { recursive: true });
                console.log(`  ${ui_js_1.sym.ok} ${ui_js_1.c.dim('created')} ${chorusDir}`);
            }
            // Seed the DB. resolveDbPath() honours CHORUS_DB_PATH so the
            // line we print matches what the daemon will actually open —
            // hardcoding ~/.chorus/chorus.db here misled users who'd set
            // the env var and then asked "where's my DB?".
            const { getDb } = await import('../../lib/db/index.js');
            await getDb();
            console.log(`  ${ui_js_1.sym.ok} ${ui_js_1.c.dim('database ready at')} ${(0, index_js_1.resolveDbPath)()}`);
            // Capture interactive PATH so the daemon can find CLIs in
            // ~/.opencode/bin etc. when it later spawns reviewers from a
            // non-interactive shell. Best-effort: skipped silently when
            // capture fails (CI, no $SHELL, exotic shells we don't model).
            try {
                const { captureInteractivePath, persistCapturedPath } = await import('../../lib/runtime-path.js');
                const captured = captureInteractivePath();
                if (captured) {
                    await persistCapturedPath(captured);
                    console.log(`  ${ui_js_1.sym.ok} ${ui_js_1.c.dim('captured shell PATH (')} ${captured.split(':').length} ${ui_js_1.c.dim('dirs)')}`);
                }
            }
            catch {
                /* non-fatal — daemon falls back to known-install probes */
            }
            const templatesDir = path_1.default.join(__dirname, '..', '..', '..', 'templates');
            if (fs_1.default.existsSync(templatesDir)) {
                const files = fs_1.default
                    .readdirSync(templatesDir)
                    .filter((f) => f.endsWith('.yaml'));
                const seeded = [];
                for (const file of files) {
                    const id = file.replace('.yaml', '');
                    const yamlPath = path_1.default.join(templatesDir, file);
                    const yamlContent = fs_1.default.readFileSync(yamlPath, 'utf-8');
                    const existing = await index_js_1.templates.getById(id);
                    if (!existing) {
                        await index_js_1.templates.create(id, yamlContent, 'builtin');
                        seeded.push(id);
                    }
                }
                if (seeded.length > 0) {
                    console.log(`  ${ui_js_1.sym.ok} ${ui_js_1.c.dim('seeded templates:')} ${ui_js_1.c.cyan(seeded.join(', '))}`);
                }
                else {
                    console.log(`  ${ui_js_1.sym.ok} ${ui_js_1.c.dim('templates already up to date')}`);
                }
            }
            // Auto-detect & register every supported orchestrator. Skipped
            // if user passes --no-register; restricted via --connect <list>.
            if (opts.register !== false) {
                await runOrchestratorAutoConnect(opts.connect);
            }
            // Reviewer-CLI presence check — separate from orchestrator wiring
            // above. Without at least one of claude/codex/gemini/opencode/
            // kimi installed OR an OpenRouter API key configured, Chorus
            // has nothing to dispatch chats to.
            const detect = await detectReviewerClis();
            if (detect.detectFailed) {
                console.log('');
                console.log(`  ${ui_js_1.c.yellow('!')} ${ui_js_1.c.bold(ui_js_1.c.yellow('CLI detection crashed:'))} ${detect.detectError ?? 'unknown error'}`);
                console.log(ui_js_1.c.dim('    Init continued anyway — verify reviewers in Settings → Voices once you start the cockpit.'));
            }
            else if (detect.clis.length === 0) {
                console.log('');
                console.log(`  ${ui_js_1.c.yellow('!')} ${ui_js_1.c.bold(ui_js_1.c.yellow('No AI CLIs detected on this machine.'))}`);
                console.log(ui_js_1.c.dim('    Chorus needs at least one of these (or an OpenRouter API key):'));
                console.log(ui_js_1.c.dim('      claude     — https://docs.anthropic.com/en/docs/claude-code'));
                console.log(ui_js_1.c.dim('      codex      — https://github.com/openai/codex'));
                console.log(ui_js_1.c.dim('      gemini     — https://github.com/google-gemini/gemini-cli'));
                console.log(ui_js_1.c.dim('      opencode   — https://opencode.ai'));
                console.log(ui_js_1.c.dim('      kimi       — https://github.com/MoonshotAI/kimi-cli'));
                console.log(ui_js_1.c.dim('      grok       — https://x.ai/cli'));
                console.log(ui_js_1.c.dim('      openrouter — Settings → Voices → Add OpenRouter (uses your API key)'));
                console.log(ui_js_1.c.dim('    Install at least one CLI, or add an OpenRouter voice after `chorus start`.'));
            }
            else {
                console.log('');
                console.log(`  ${ui_js_1.sym.ok} ${ui_js_1.c.dim('AI CLIs ready:')} ${ui_js_1.c.cyan(detect.clis.join(', '))}`);
            }
            console.log('');
            console.log((0, ui_js_1.header)(ui_js_1.sym.ok, 'Chorus initialized'));
            console.log('');
            console.log(`  ${ui_js_1.c.dim('Next:')} ${ui_js_1.c.bold('chorus start')} ${ui_js_1.c.dim('— bring up the daemon and cockpit.')}`);
            console.log(`  ${ui_js_1.c.dim('Then restart any editor we just registered (Claude Code, etc.) so it picks up the MCP server.')}`);
            console.log('');
        }
        catch (error) {
            console.error(`${ui_js_1.sym.err} ${ui_js_1.c.red('Initialization failed:')}`, error);
            process.exit(1);
        }
    });
}
//# sourceMappingURL=init.js.map