"use strict";
// src/cli/ProviderCommand.ts
// v1.14.0 — `openlife provider {list,detect,doctor,setup,use,models,quick,set-mode,set-preference}`.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerProviderCommands = registerProviderCommands;
const readline = __importStar(require("readline"));
async function listCmd() {
    const { ProviderProbe } = await Promise.resolve().then(() => __importStar(require('../orchestrator/router/ProviderProbe')));
    const entries = ProviderProbe.run();
    for (const e of entries) {
        const cli = e.cliAvailable ? '✓' : '✗';
        const api = e.apiAvailable ? '✓' : '✗';
        console.log(`${cli} cli  ${api} api  ${e.provider}  (binary: ${e.cliBinary || '-'})  models: ${e.models.map(m => `${m.id}[${m.tier}]`).join(', ')}`);
    }
}
async function detectCmd() {
    const { ProviderProbe } = await Promise.resolve().then(() => __importStar(require('../orchestrator/router/ProviderProbe')));
    const entries = ProviderProbe.run({ force: true });
    for (const e of entries) {
        const status = e.cliAvailable ? '✓ available' : e.apiAvailable ? '✓ api-only' : '✗ not installed';
        console.log(`${e.provider.padEnd(14)} ${status}`);
    }
}
async function doctorCmd() {
    const { ProviderProbe } = await Promise.resolve().then(() => __importStar(require('../orchestrator/router/ProviderProbe')));
    const { readRouterConfig } = await Promise.resolve().then(() => __importStar(require('../orchestrator/router/ModelTierRouter')));
    const entries = ProviderProbe.run({ force: true });
    const cfg = readRouterConfig();
    console.log(`mode: ${cfg.mode || '<not set, falls back to cli-only>'}`);
    console.log(`preference: ${(cfg.preference || []).join(', ') || '<default>'}`);
    console.log('');
    for (const e of entries) {
        const cli = e.cliAvailable ? '✓' : '✗';
        const api = e.apiAvailable ? '✓' : '✗';
        console.log(`${cli} cli ${api} api  ${e.provider}`);
        if (!e.cliAvailable && e.cliBinary) {
            const hint = installHint(e.provider);
            if (hint)
                console.log(`    → ${hint}`);
        }
    }
}
function installHint(provider) {
    switch (provider) {
        case 'openai-cli': return 'Install Codex: npm install -g @openai/codex && codex login';
        case 'gemini-cli': return 'Install Gemini CLI: see https://aistudio.google.com/app/apikey then `gemini auth`';
        case 'anthropic': return 'Install Claude CLI: https://docs.anthropic.com/claude/docs/claude-cli, then `claude /login`';
        case 'ollama': return 'Install Ollama: https://ollama.ai/download, then `ollama pull nomic-embed-text`';
        default: return null;
    }
}
async function setupCmd() {
    const { ProviderProbe } = await Promise.resolve().then(() => __importStar(require('../orchestrator/router/ProviderProbe')));
    const { readRouterConfig, writeRouterConfig } = await Promise.resolve().then(() => __importStar(require('../orchestrator/router/ModelTierRouter')));
    const entries = ProviderProbe.run({ force: true });
    const available = entries.filter(e => e.cliAvailable);
    if (available.length === 0) {
        console.log('No CLI provider detected. Install one of:');
        console.log('  - claude (anthropic): https://docs.anthropic.com/claude/docs/claude-cli');
        console.log('  - gemini (google):    https://aistudio.google.com/app/apikey');
        console.log('  - codex (openai):     npm install -g @openai/codex');
        console.log('  - ollama (local):     https://ollama.ai/download');
        process.exitCode = 1;
        return;
    }
    const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
    const ask = (q) => new Promise((res) => rl.question(q, res));
    console.log('\nDetected CLIs:');
    available.forEach((e, i) => {
        console.log(`  ${i + 1}) ${e.provider} (${e.cliBinary}) — models: ${e.models.map(m => m.id).join(', ')}`);
    });
    const primarySel = await ask(`\nPrimary CLI [1-${available.length}, default 1]: `);
    const primaryIdx = Math.max(0, Math.min(available.length - 1, (Number(primarySel) || 1) - 1));
    const primary = available[primaryIdx];
    const fastDefault = primary.models.find(m => m.tier === 'fast')?.id || primary.models[0]?.id || '';
    const smartDefault = primary.models.find(m => m.tier === 'smart')?.id || primary.models[primary.models.length - 1]?.id || '';
    const fast = (await ask(`Fast tier model for ${primary.provider} [${fastDefault}]: `)).trim() || fastDefault;
    const smart = (await ask(`Smart tier model for ${primary.provider} [${smartDefault}]: `)).trim() || smartDefault;
    const order = [primary.provider, ...available.filter(e => e.provider !== primary.provider).map(e => e.provider)];
    const cfg = readRouterConfig();
    cfg.mode = cfg.mode || 'cli-only';
    cfg.preference = order;
    cfg.fastModel = { ...(cfg.fastModel || {}), [primary.provider]: fast };
    cfg.smartModel = { ...(cfg.smartModel || {}), [primary.provider]: smart };
    writeRouterConfig(cfg);
    rl.close();
    console.log(`\n[OPENLIFE] Saved ~/.openlife/router.json (mode=${cfg.mode}, primary=${primary.provider}).`);
}
async function useCmd(provider, opts) {
    const { readRouterConfig, writeRouterConfig } = await Promise.resolve().then(() => __importStar(require('../orchestrator/router/ModelTierRouter')));
    const cfg = readRouterConfig();
    cfg.preference = [provider, ...((cfg.preference || []).filter(p => p !== provider))];
    if (opts.fast)
        cfg.fastModel = { ...(cfg.fastModel || {}), [provider]: opts.fast };
    if (opts.smart)
        cfg.smartModel = { ...(cfg.smartModel || {}), [provider]: opts.smart };
    cfg.mode = cfg.mode || 'cli-only';
    writeRouterConfig(cfg);
    console.log(`[OPENLIFE] Primary provider → ${provider}${opts.fast ? `, fast=${opts.fast}` : ''}${opts.smart ? `, smart=${opts.smart}` : ''}`);
}
async function modelsCmd(provider) {
    const { findProvider } = await Promise.resolve().then(() => __importStar(require('../orchestrator/router/ProviderCapabilityCatalog')));
    const entry = findProvider(provider);
    if (!entry) {
        console.error(`unknown provider: ${provider}`);
        process.exitCode = 1;
        return;
    }
    for (const m of entry.models)
        console.log(`${m.tier.padEnd(6)} ${m.id}`);
}
async function setModeCmd(mode) {
    const { readRouterConfig, writeRouterConfig } = await Promise.resolve().then(() => __importStar(require('../orchestrator/router/ModelTierRouter')));
    if (!['cli-only', 'hybrid', 'api-only', 'local-only'].includes(mode)) {
        console.error(`unknown mode: ${mode}. Pick: cli-only | hybrid | api-only | local-only`);
        process.exitCode = 1;
        return;
    }
    const cfg = readRouterConfig();
    cfg.mode = mode;
    writeRouterConfig(cfg);
    console.log(`[OPENLIFE] mode → ${mode}`);
}
async function setPrefCmd(list) {
    const { readRouterConfig, writeRouterConfig } = await Promise.resolve().then(() => __importStar(require('../orchestrator/router/ModelTierRouter')));
    const cfg = readRouterConfig();
    cfg.preference = list.split(',').map(s => s.trim()).filter(Boolean);
    writeRouterConfig(cfg);
    console.log(`[OPENLIFE] preference → ${cfg.preference.join(', ')}`);
}
function registerProviderCommands(program) {
    const p = program
        .command('provider')
        .description('v1.14.0 — Per-CLI tier router, zero-config first-run wizard');
    p.command('list')
        .description('List known providers + cached availability')
        .action(() => { void listCmd(); });
    p.command('detect')
        .description('Re-run availability probe and update cache')
        .action(() => { void detectCmd(); });
    p.command('doctor')
        .description('Status of every provider + actionable install hints')
        .action(() => { void doctorCmd(); });
    p.command('setup')
        .description('Interactive wizard: pick CLI + fast/smart tier models')
        .action(() => { void setupCmd(); });
    p.command('use <provider>')
        .description('Make <provider> primary; optionally pin fast/smart models')
        .option('--fast <model>', 'Model id for the fast tier')
        .option('--smart <model>', 'Model id for the smart tier')
        .action((provider, opts) => { void useCmd(provider, opts); });
    p.command('models <provider>')
        .description('List the tier roster of <provider>')
        .action((provider) => { void modelsCmd(provider); });
    p.command('set-mode <mode>')
        .description('cli-only (default) | hybrid | api-only | local-only')
        .action((mode) => { void setModeCmd(mode); });
    p.command('set-preference <list>')
        .description('Comma-separated provider order (e.g. anthropic,gemini-cli,openai-cli)')
        .action((list) => { void setPrefCmd(list); });
}
