"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleCatalogReset = exports.handleCatalogJson = exports.handleCatalogRefresh = exports.handleCatalogStatus = void 0;
const ui_1 = require("../../utils/ui");
const catalog_cache_1 = require("../../cliproxy/services/catalog-cache");
const catalog_routing_1 = require("../../cliproxy/services/catalog-routing");
const managed_model_prefixes_1 = require("../../cliproxy/ai-providers/managed-model-prefixes");
const proxy_target_resolver_1 = require("../../cliproxy/proxy/proxy-target-resolver");
/** Fetch model definitions from CLIProxyAPI for all syncable providers */
async function fetchRemoteCatalogs(verbose) {
    const target = (0, proxy_target_resolver_1.getProxyTarget)();
    if (verbose) {
        console.log((0, ui_1.dim)(`  Connected to ${target.protocol}://${target.host}:${target.port} (${target.isRemote ? 'remote' : 'local'})`));
    }
    const result = await (0, catalog_cache_1.refreshCatalogFromProxy)();
    if (verbose && result) {
        for (const provider of catalog_cache_1.SYNCABLE_PROVIDERS) {
            const models = result[provider];
            if (models?.length) {
                console.log((0, ui_1.dim)(`  ${provider}: ${models.length} models`));
            }
        }
    }
    return result;
}
/** Show catalog status */
async function handleCatalogStatus(verbose) {
    await (0, ui_1.initUI)();
    console.log('');
    console.log((0, ui_1.header)('Model Catalog'));
    console.log('');
    let routingSnapshot = null;
    if (verbose) {
        try {
            await (0, managed_model_prefixes_1.ensureManagedModelPrefixes)();
            routingSnapshot = await (0, catalog_routing_1.getCatalogRoutingSnapshot)();
        }
        catch {
            routingSnapshot = null;
        }
    }
    const cacheAge = routingSnapshot?.cacheAge ?? (0, catalog_cache_1.getCacheAge)();
    if (cacheAge) {
        console.log(`  Cache: ${(0, ui_1.color)('synced', 'success')} (${cacheAge})`);
    }
    else {
        console.log(`  Cache: ${(0, ui_1.color)('static only', 'warning')} (no sync)`);
    }
    console.log('');
    console.log((0, ui_1.subheader)('Providers:'));
    for (const provider of catalog_cache_1.SYNCABLE_PROVIDERS) {
        const catalog = routingSnapshot?.catalogs[provider] ?? (0, catalog_cache_1.getResolvedCatalog)(provider);
        if (catalog) {
            const count = catalog.models.length;
            const routing = routingSnapshot?.routing[provider];
            const suffix = renderRoutingSummary(routing);
            console.log(`  ${(0, ui_1.color)(catalog.displayName.padEnd(20), 'command')} ${count} models${suffix}`);
            if (verbose) {
                renderVerboseRouting(provider, catalog.models, routing);
            }
        }
    }
    console.log('');
    if (!cacheAge) {
        console.log((0, ui_1.dim)('  Run "ccs cliproxy catalog refresh" to sync from CLIProxy'));
    }
    console.log('');
}
exports.handleCatalogStatus = handleCatalogStatus;
function renderRoutingSummary(routing) {
    if (!routing) {
        return '';
    }
    const parts = [`prefix ${routing.prefix}`];
    if (routing.shadowedCount > 0) {
        parts.push(`${routing.shadowedCount} shadowed`);
    }
    if (routing.prefixOnlyCount > 0) {
        parts.push(`${routing.prefixOnlyCount} prefix-only`);
    }
    return parts.length > 0 ? `  ${(0, ui_1.dim)(`(${parts.join(', ')})`)}` : '';
}
function renderVerboseRouting(provider, models, routing) {
    if (!routing) {
        for (const model of models) {
            console.log((0, ui_1.dim)(`    - ${model.id} (${model.name})`));
        }
        return;
    }
    const routingMap = new Map(routing.models.map((hint) => [hint.modelId, hint]));
    for (const model of models) {
        const hint = routingMap.get(model.id);
        console.log((0, ui_1.dim)(`    - ${model.id} (${model.name})`));
        if (!hint) {
            continue;
        }
        console.log((0, ui_1.dim)(`      ${hint.pinnedAvailable ? 'preferred' : 'suggested'}: ${hint.recommendedModelId}`));
        if (hint.unprefixedStatus === 'safe') {
            console.log((0, ui_1.dim)(`      unprefixed: resolves to ${routing.displayName}`));
            continue;
        }
        if (hint.unprefixedStatus === 'shadowed' && hint.effectiveDisplayName) {
            console.log((0, ui_1.dim)(`      unprefixed: currently resolves to ${hint.effectiveDisplayName}`));
            continue;
        }
        console.log((0, ui_1.dim)(`      unprefixed: not advertised, use ${hint.recommendedModelId}`));
    }
    if (provider === 'gemini' || provider === 'agy') {
        console.log((0, ui_1.dim)(`      short prefix stays backend-pinned even when unprefixed names overlap.`));
    }
}
/** Refresh catalog from CLIProxyAPI */
async function handleCatalogRefresh(verbose) {
    await (0, ui_1.initUI)();
    console.log('');
    console.log((0, ui_1.header)('Catalog Refresh'));
    console.log('');
    const result = await fetchRemoteCatalogs(verbose);
    if (!result) {
        console.log('  Failed to fetch live catalogs. Static catalog unchanged.');
        console.log('');
        return;
    }
    // Show summary
    let totalModels = 0;
    for (const [provider, models] of Object.entries(result)) {
        const merged = (0, catalog_cache_1.getResolvedCatalog)(provider);
        const mergedCount = merged?.models.length ?? 0;
        console.log(`  ${(0, ui_1.color)(provider.padEnd(12), 'command')} ${models.length} live -> ${mergedCount} merged`);
        totalModels += mergedCount;
    }
    console.log('');
    console.log(`  ${(0, ui_1.color)('[OK]', 'success')} Catalog synced (${totalModels} total models)`);
    console.log('');
}
exports.handleCatalogRefresh = handleCatalogRefresh;
/**
 * Output catalog as JSON for programmatic consumption.
 * Used by OnSteroids and other tools to get available models per provider.
 * Format: { [providerName: string]: CatalogJsonModel[] }
 */
function handleCatalogJson() {
    const catalogs = (0, catalog_cache_1.getAllResolvedCatalogs)();
    const result = {};
    for (const [provider, catalog] of Object.entries(catalogs)) {
        if (!catalog) {
            continue;
        }
        result[provider] = catalog.models.map((m) => {
            const entry = { id: m.id, name: m.name };
            if (m.tier !== undefined)
                entry.tier = m.tier;
            if (m.description !== undefined)
                entry.description = m.description;
            if (m.deprecated !== undefined)
                entry.deprecated = m.deprecated;
            if (m.deprecationReason !== undefined)
                entry.deprecationReason = m.deprecationReason;
            if (m.broken !== undefined)
                entry.broken = m.broken;
            if (m.issueUrl !== undefined)
                entry.issueUrl = m.issueUrl;
            if (m.thinking !== undefined)
                entry.thinking = m.thinking;
            if (m.extendedContext !== undefined)
                entry.extendedContext = m.extendedContext;
            if (m.nativeImageInput !== undefined)
                entry.nativeImageInput = m.nativeImageInput;
            return entry;
        });
    }
    console.log(JSON.stringify(result));
}
exports.handleCatalogJson = handleCatalogJson;
/** Reset catalog cache */
async function handleCatalogReset() {
    await (0, ui_1.initUI)();
    console.log('');
    const cleared = (0, catalog_cache_1.clearCatalogCache)();
    if (cleared) {
        console.log(`  ${(0, ui_1.color)('[OK]', 'success')} Catalog cache cleared. Using static catalog.`);
    }
    else {
        console.log('  No cache to clear.');
    }
    console.log('');
}
exports.handleCatalogReset = handleCatalogReset;
//# sourceMappingURL=catalog-subcommand.js.map