import { existsSync } from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
import { loadLiteLlmCatalog as loadLiteLlmCatalogTokentally, resolveLiteLlmMaxInputTokens as resolveLiteLlmMaxInputTokensTokentally, resolveLiteLlmMaxOutputTokens as resolveLiteLlmMaxOutputTokensTokentally, resolveLiteLlmPricing as resolveLiteLlmPricingTokentally, } from "tokentally/node";
function withDefaultCacheDir(env) {
    if (typeof env.TOKENTALLY_CACHE_DIR === "string" && env.TOKENTALLY_CACHE_DIR.trim().length > 0) {
        return env;
    }
    const home = env.HOME?.trim();
    if (!home)
        return env;
    return { ...env, TOKENTALLY_CACHE_DIR: path.join(home, ".summarize", "cache") };
}
function resolveCacheDir(env) {
    const effectiveEnv = withDefaultCacheDir(env);
    const override = effectiveEnv.TOKENTALLY_CACHE_DIR?.trim();
    if (override)
        return override;
    const home = effectiveEnv.HOME?.trim();
    return home ? path.join(home, ".tokentally", "cache") : null;
}
function cacheCatalogPath(env) {
    const cacheDir = resolveCacheDir(env);
    return cacheDir ? path.join(cacheDir, "litellm-model_prices_and_context_window.json") : null;
}
function isRecord(value) {
    return typeof value === "object" && value !== null && !Array.isArray(value);
}
export async function loadLiteLlmCatalog({ env, fetchImpl, nowMs = Date.now(), }) {
    return loadLiteLlmCatalogTokentally({
        env: withDefaultCacheDir(env),
        fetchImpl,
        nowMs,
    });
}
export async function loadCachedLiteLlmCatalog({ env, }) {
    const catalogPath = cacheCatalogPath(env);
    if (!catalogPath || !existsSync(catalogPath))
        return null;
    try {
        const raw = await fs.readFile(catalogPath, "utf8");
        const parsed = JSON.parse(raw);
        return isRecord(parsed) ? parsed : null;
    }
    catch {
        return null;
    }
}
export function resolveLiteLlmPricingForModelId(catalog, modelId) {
    return resolveLiteLlmPricingTokentally(catalog, modelId);
}
export function resolveLiteLlmMaxOutputTokensForModelId(catalog, modelId) {
    return resolveLiteLlmMaxOutputTokensTokentally(catalog, modelId);
}
export function resolveLiteLlmMaxInputTokensForModelId(catalog, modelId) {
    return resolveLiteLlmMaxInputTokensTokentally(catalog, modelId);
}
//# sourceMappingURL=litellm.js.map