"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getKnownModelsDevModels = exports.resolveModelsDevPricing = exports.normalizeModelsDevProviderId = void 0;
const registry_cache_1 = require("./registry-cache");
const PROVIDER_ALIASES = {
    agy: 'google',
    antigravity: 'google',
    claude: 'anthropic',
    codex: 'openai',
    copilot: 'github-copilot',
    gemini: 'google',
    ghcp: 'github-copilot',
    github: 'github-copilot',
    kimi: 'moonshotai',
    moonshot: 'moonshotai',
    qwen: 'alibaba',
};
function normalizeId(value) {
    return value.trim().toLowerCase();
}
function isModelEntry(value) {
    return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function normalizeModelsDevProviderId(provider) {
    if (!provider)
        return undefined;
    const normalized = normalizeId(provider);
    return PROVIDER_ALIASES[normalized] ?? normalized;
}
exports.normalizeModelsDevProviderId = normalizeModelsDevProviderId;
function splitProviderPrefix(model) {
    const trimmed = model.trim();
    const slashIndex = trimmed.indexOf('/');
    if (slashIndex <= 0)
        return { model: trimmed };
    return {
        provider: trimmed.slice(0, slashIndex),
        model: trimmed.slice(slashIndex + 1),
    };
}
function stripClaudeDateSuffix(model) {
    if (!model.startsWith('claude-'))
        return model;
    return model.replace(/-\d{8}(?=-thinking(?:$|:))/g, '').replace(/-\d{8}(?=$|:)/g, '');
}
function getModelCandidates(model) {
    const normalized = normalizeId(model);
    const baseModel = normalized.split(':')[0];
    const candidates = [normalized];
    if (baseModel !== normalized)
        candidates.push(baseModel);
    for (const candidate of [...candidates]) {
        const stripped = stripClaudeDateSuffix(candidate);
        if (stripped !== candidate && !candidates.includes(stripped)) {
            candidates.push(stripped);
        }
    }
    return candidates;
}
function findProvider(registry, provider) {
    const normalizedProvider = normalizeModelsDevProviderId(provider);
    if (!normalizedProvider)
        return undefined;
    return registry[normalizedProvider];
}
function findModel(provider, model) {
    const models = provider.models;
    if (!models)
        return undefined;
    const normalizedEntries = new Map();
    for (const [key, value] of Object.entries(models)) {
        if (!isModelEntry(value))
            continue;
        normalizedEntries.set(normalizeId(key), value);
        if (typeof value.id === 'string')
            normalizedEntries.set(normalizeId(value.id), value);
    }
    for (const candidate of getModelCandidates(model)) {
        const match = normalizedEntries.get(candidate);
        if (match)
            return match;
    }
    return undefined;
}
function toNumber(value) {
    return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
}
function toPricing(cost) {
    const input = toNumber(cost?.input);
    const output = toNumber(cost?.output);
    if (input === undefined || output === undefined)
        return undefined;
    return {
        inputPerMillion: input,
        outputPerMillion: output,
        cacheCreationPerMillion: toNumber(cost?.cache_write) ?? 0,
        cacheReadPerMillion: toNumber(cost?.cache_read) ?? 0,
    };
}
function samePricing(left, right) {
    return (left.inputPerMillion === right.inputPerMillion &&
        left.outputPerMillion === right.outputPerMillion &&
        left.cacheCreationPerMillion === right.cacheCreationPerMillion &&
        left.cacheReadPerMillion === right.cacheReadPerMillion);
}
function resolveProviderModel(registry, providerId, model) {
    const provider = findProvider(registry, providerId);
    if (!provider)
        return undefined;
    const entry = findModel(provider, model);
    const pricing = toPricing(entry?.cost);
    if (!entry || !pricing)
        return undefined;
    return { provider: provider.id, model: entry.id, pricing };
}
function resolveUnambiguousModel(registry, model) {
    const matches = [];
    for (const provider of Object.values(registry)) {
        const match = resolveProviderModel(registry, provider.id, model);
        if (match)
            matches.push(match);
    }
    if (matches.length === 0)
        return undefined;
    const first = matches[0];
    if (matches.every((match) => samePricing(first.pricing, match.pricing))) {
        return first;
    }
    return undefined;
}
function resolveModelsDevPricing(model, options = {}) {
    const registry = (0, registry_cache_1.getCachedModelsDevRegistry)({ allowStale: true });
    if (!registry)
        return undefined;
    const prefixed = splitProviderPrefix(model);
    const provider = options.provider ?? prefixed.provider;
    const modelId = prefixed.model;
    if (provider) {
        return resolveProviderModel(registry, provider, modelId);
    }
    return resolveUnambiguousModel(registry, modelId);
}
exports.resolveModelsDevPricing = resolveModelsDevPricing;
function getKnownModelsDevModels() {
    const registry = (0, registry_cache_1.getCachedModelsDevRegistry)({ allowStale: true });
    if (!registry)
        return [];
    const ids = new Set();
    for (const provider of Object.values(registry)) {
        for (const model of Object.values(provider.models ?? {})) {
            if (!model || typeof model !== 'object')
                continue;
            if (typeof model.id === 'string')
                ids.add(`${provider.id}/${model.id}`);
        }
    }
    return Array.from(ids).sort((a, b) => a.localeCompare(b));
}
exports.getKnownModelsDevModels = getKnownModelsDevModels;
//# sourceMappingURL=pricing-resolver.js.map