"use strict";
/**
 * OpenRouter Interactive Model Picker
 * CLI interface for browsing and selecting OpenRouter models
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.pickOpenRouterModel = void 0;
const prompt_1 = require("../../utils/prompt");
const ui_1 = require("../../utils/ui");
const openrouter_catalog_1 = require("./openrouter-catalog");
/** Interactive model picker */
async function pickOpenRouterModel() {
    // Fetch models with spinner
    const s = await (0, ui_1.spinner)('Fetching OpenRouter models...');
    let models;
    try {
        models = await (0, openrouter_catalog_1.fetchOpenRouterModels)();
        s.succeed(`Loaded ${models.length} models from OpenRouter`);
    }
    catch (error) {
        s.fail(`Failed to fetch models: ${error.message}`);
        return null;
    }
    // Search loop
    let selectedModel = null;
    while (!selectedModel) {
        const query = await prompt_1.InteractivePrompt.input('Search models (or press Enter to see popular)', {
            default: '',
        });
        const results = (0, openrouter_catalog_1.searchModels)(models, query);
        if (results.length === 0) {
            console.log((0, ui_1.warn)('No models found. Try a different search term.'));
            continue;
        }
        // Display results in table
        console.log('');
        const rows = results.map((m, i) => [
            String(i + 1),
            m.id.length > 35 ? m.id.slice(0, 32) + '...' : m.id,
            (0, openrouter_catalog_1.formatPricingPair)(m.pricing),
            (0, openrouter_catalog_1.formatContext)(m.context_length),
        ]);
        console.log((0, ui_1.table)(rows, {
            head: ['#', 'Model ID', 'Price (prompt/completion)', 'Context'],
        }));
        console.log('');
        // Get selection
        const selection = await prompt_1.InteractivePrompt.input(`Select model [1-${results.length}] or search again`, { default: '1' });
        const index = parseInt(selection, 10) - 1;
        if (index >= 0 && index < results.length) {
            selectedModel = results[index];
        }
        else if (selection.trim()) {
            // Treat as new search
            const newResults = (0, openrouter_catalog_1.searchModels)(models, selection);
            if (newResults.length === 1) {
                selectedModel = newResults[0];
            }
        }
    }
    console.log('');
    console.log((0, ui_1.info)(`Selected: ${(0, ui_1.color)(selectedModel.id, 'info')}`));
    // Ask about tier mapping
    const configureTiers = await prompt_1.InteractivePrompt.confirm('Configure model tier mapping (opus/sonnet/haiku)?', { default: false });
    if (!configureTiers) {
        return { model: selectedModel.id };
    }
    // Tier mapping
    console.log('');
    console.log((0, ui_1.dim)('Leave blank to skip a tier.'));
    const tierMapping = {
        opus: await prompt_1.InteractivePrompt.input('Opus tier model', {
            default: suggestTier(selectedModel.id, 'opus', models),
        }),
        sonnet: await prompt_1.InteractivePrompt.input('Sonnet tier model', {
            default: selectedModel.id,
        }),
        haiku: await prompt_1.InteractivePrompt.input('Haiku tier model', {
            default: suggestTier(selectedModel.id, 'haiku', models),
        }),
    };
    // Clean empty values
    const cleanMapping = {
        opus: tierMapping.opus || undefined,
        sonnet: tierMapping.sonnet || undefined,
        haiku: tierMapping.haiku || undefined,
    };
    return {
        model: selectedModel.id,
        tierMapping: cleanMapping,
    };
}
exports.pickOpenRouterModel = pickOpenRouterModel;
/** Suggest tier model based on provider */
function suggestTier(selectedId, tier, models) {
    const [provider] = selectedId.split('/');
    const providerModels = models.filter((m) => m.id.startsWith(`${provider}/`));
    if (providerModels.length < 2)
        return '';
    // Sort by price
    const sorted = [...providerModels].sort((a, b) => {
        const priceA = parseFloat(a.pricing.prompt) || 0;
        const priceB = parseFloat(b.pricing.prompt) || 0;
        return priceB - priceA; // Descending
    });
    if (tier === 'opus') {
        return sorted[0]?.id ?? '';
    }
    else {
        return sorted[sorted.length - 1]?.id ?? '';
    }
}
//# sourceMappingURL=openrouter-picker.js.map