"use strict";
/**
 * OpenRouter Model Catalog Fetcher
 * Fetches model list from OpenRouter API for CLI use
 */
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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isOpenRouterUrl = exports.searchModels = exports.formatContext = exports.formatPricingPair = exports.formatPrice = exports.fetchOpenRouterModels = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const config_loader_facade_1 = require("../../config/config-loader-facade");
const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/models';
function getCacheFile() {
    return path.join((0, config_loader_facade_1.getCcsDir)(), 'openrouter-models-cache.json');
}
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
/** Check if cached data is valid */
function getCachedModels() {
    try {
        const cacheFile = getCacheFile();
        if (!fs.existsSync(cacheFile))
            return null;
        const data = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
        if (Date.now() - data.fetchedAt > CACHE_TTL_MS)
            return null;
        return data.models;
    }
    catch {
        return null;
    }
}
/** Save models to cache */
function setCachedModels(models) {
    try {
        const cacheFile = getCacheFile();
        const dir = path.dirname(cacheFile);
        if (!fs.existsSync(dir))
            fs.mkdirSync(dir, { recursive: true });
        fs.writeFileSync(cacheFile, JSON.stringify({
            models,
            fetchedAt: Date.now(),
        }));
    }
    catch {
        // Ignore cache write errors
    }
}
/** Fetch models from OpenRouter API */
async function fetchOpenRouterModels() {
    // Try cache first
    const cached = getCachedModels();
    if (cached)
        return cached;
    // Fetch from API
    const response = await fetch(OPENROUTER_API_URL);
    if (!response.ok) {
        throw new Error(`Failed to fetch OpenRouter models: ${response.status}`);
    }
    const data = (await response.json());
    const models = data.data.map((m) => ({
        id: m.id,
        name: m.name,
        description: m.description,
        context_length: m.context_length,
        pricing: m.pricing,
    }));
    // Cache for next time
    setCachedModels(models);
    return models;
}
exports.fetchOpenRouterModels = fetchOpenRouterModels;
/** Format price per token to per million */
function formatPrice(perToken) {
    const value = parseFloat(perToken);
    if (isNaN(value) || value === 0)
        return 'Free';
    const perMillion = value * 1000000;
    if (perMillion < 0.01)
        return '<$0.01';
    if (perMillion < 1)
        return `$${perMillion.toFixed(2)}`;
    return `$${perMillion.toFixed(perMillion < 10 ? 2 : 0)}`;
}
exports.formatPrice = formatPrice;
/** Format pricing pair */
function formatPricingPair(pricing) {
    return `${formatPrice(pricing.prompt)}/${formatPrice(pricing.completion)}`;
}
exports.formatPricingPair = formatPricingPair;
/** Format context length */
function formatContext(length) {
    if (length >= 1000000)
        return `${(length / 1000000).toFixed(1)}M`;
    return `${Math.round(length / 1000)}K`;
}
exports.formatContext = formatContext;
/** Search models */
function searchModels(models, query) {
    if (!query.trim())
        return models.slice(0, 20); // Show first 20 if no query
    const q = query.toLowerCase();
    return models
        .filter((m) => m.id.toLowerCase().includes(q) || m.name.toLowerCase().includes(q))
        .slice(0, 20); // Limit to 20 results
}
exports.searchModels = searchModels;
/** Check if URL is OpenRouter */
function isOpenRouterUrl(url) {
    return url.toLowerCase().includes('openrouter.ai');
}
exports.isOpenRouterUrl = isOpenRouterUrl;
//# sourceMappingURL=openrouter-catalog.js.map