import { getFridayAgentForwardRuntime } from "../../agent-forward-runtime.js";
import { splitModelRef } from "../../session/session-manager.js";
import { extractBearerToken } from "../middleware/auth.js";
function resolveConfiguredModels() {
    const rt = getFridayAgentForwardRuntime();
    if (!rt)
        return { models: [], defaultModel: "" };
    const cfg = rt.getConfig();
    const providerMeta = buildProviderModelMeta(cfg);
    const agents = cfg?.agents;
    const agentDefaults = agents?.defaults;
    const agentModels = agentDefaults?.models;
    const seen = new Set();
    const entries = [];
    if (agentModels) {
        for (const [modelKey, info] of Object.entries(agentModels)) {
            const split = splitModelRef(modelKey);
            if (!split.provider)
                continue;
            const meta = providerMeta.get(modelKey);
            seen.add(modelKey);
            entries.push({
                id: modelKey,
                name: typeof info?.alias === "string" ? info.alias : meta?.name ?? split.modelId,
                provider: split.provider,
                reasoning: meta?.reasoning,
                contextWindow: meta?.contextWindow,
                maxTokens: meta?.maxTokens,
            });
        }
    }
    for (const agent of agents?.list ?? []) {
        const primaryModel = typeof agent?.model === "string" ? agent.model : undefined;
        if (primaryModel && !seen.has(primaryModel)) {
            const split = splitModelRef(primaryModel);
            const meta = providerMeta.get(primaryModel);
            entries.push({
                id: primaryModel,
                name: meta?.name ?? split.modelId,
                provider: split.provider ?? "",
                reasoning: meta?.reasoning,
                contextWindow: meta?.contextWindow,
                maxTokens: meta?.maxTokens,
            });
        }
    }
    const agentModel = agentDefaults?.model;
    let defaultModel = typeof agentModel === "string" && agentModel.trim()
        ? agentModel.trim()
        : typeof agentModel?.primary === "string"
            ? agentModel.primary
            : "";
    if (!defaultModel && entries.length > 0) {
        defaultModel = entries[0].id;
    }
    if (defaultModel && !seen.has(defaultModel)) {
        const split = splitModelRef(defaultModel);
        const meta = providerMeta.get(defaultModel);
        entries.unshift({
            id: defaultModel,
            name: meta?.name ?? split.modelId,
            provider: split.provider ?? "",
            reasoning: meta?.reasoning,
            contextWindow: meta?.contextWindow,
            maxTokens: meta?.maxTokens,
        });
    }
    return { models: entries, defaultModel };
}
function buildProviderModelMeta(cfg) {
    const meta = new Map();
    const models = cfg?.models;
    const providers = models?.providers;
    if (providers) {
        for (const [providerId, provider] of Object.entries(providers)) {
            const providerModels = provider?.models;
            if (!Array.isArray(providerModels))
                continue;
            for (const m of providerModels) {
                const modelId = typeof m.id === "string" ? m.id : typeof m.name === "string" ? m.name : "";
                if (!modelId)
                    continue;
                meta.set(`${providerId}/${modelId}`, {
                    name: typeof m.name === "string" ? m.name : undefined,
                    reasoning: typeof m.reasoning === "boolean" ? m.reasoning : undefined,
                    contextWindow: typeof m.contextWindow === "number" ? m.contextWindow : undefined,
                    maxTokens: typeof m.maxTokens === "number" ? m.maxTokens : undefined,
                });
            }
        }
    }
    return meta;
}
export async function handleModelsList(req, res) {
    if (req.method !== "GET") {
        res.statusCode = 405;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Method Not Allowed" }));
        return true;
    }
    const token = extractBearerToken(req);
    if (!token) {
        res.statusCode = 401;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Unauthorized: bearer token mismatch" }));
        return true;
    }
    const { models, defaultModel } = resolveConfiguredModels();
    res.statusCode = 200;
    res.setHeader("Content-Type", "application/json");
    res.end(JSON.stringify({ ok: true, models, defaultModel }));
    return true;
}
