import { findCodexBinary } from '../codex-adapter.js';
import { runProcess } from '../fsx.js';
const FALLBACK_EFFORT_ORDER = ['minimal', 'low', 'medium', 'high', 'xhigh'];
export async function collectCodexModelMetadata(input = {}) {
    if (process.env.SKS_CODEX_MODEL_METADATA_FAKE === '1') {
        const advertised = normalizeAdvertisedEfforts(process.env.SKS_CODEX_MODEL_EFFORTS || 'low,medium,high,xhigh');
        return metadata(String(input.model || process.env.SKS_CODEX_MODEL || 'gpt-5.5'), advertised, 'medium', 'app-server', []);
    }
    const model = String(input.model || process.env.SKS_CODEX_MODEL || process.env.CODEX_MODEL || 'gpt-5.5');
    const appServer = await readAppServerMetadata(model);
    if (appServer)
        return appServer;
    const cli = await readCodexCliMetadata(model);
    if (cli)
        return cli;
    const envEfforts = normalizeAdvertisedEfforts(process.env.SKS_CODEX_MODEL_EFFORTS || '');
    if (envEfforts.length)
        return metadata(model, envEfforts, process.env.SKS_CODEX_MODEL_DEFAULT_EFFORT || 'medium', 'env', []);
    return metadata(model, FALLBACK_EFFORT_ORDER, 'medium', 'fallback', ['codex_model_metadata_unavailable']);
}
async function readAppServerMetadata(model) {
    const url = String(process.env.CODEX_APP_SERVER_METADATA_URL || process.env.SKS_CODEX_APP_SERVER_METADATA_URL || '').trim();
    if (!url)
        return null;
    try {
        const response = await fetch(url, { signal: AbortSignal.timeout(3000) });
        if (!response.ok)
            return null;
        const payload = await response.json();
        return normalizePayload(payload, model, 'app-server');
    }
    catch {
        return null;
    }
}
async function readCodexCliMetadata(model) {
    const bin = await findCodexBinary();
    if (!bin)
        return null;
    const commands = [
        ['model', 'metadata', '--json'],
        ['debug', 'model-metadata', '--json'],
        ['capabilities', '--json']
    ];
    for (const args of commands) {
        const result = await runProcess(bin, args, { timeoutMs: 3000, maxOutputBytes: 64 * 1024 }).catch(() => null);
        if (!result || result.code !== 0)
            continue;
        try {
            const payload = JSON.parse(`${result.stdout || ''}${result.stderr || ''}`.trim() || '{}');
            const normalized = normalizePayload(payload, model, 'codex-cli');
            if (normalized.advertised_efforts.length)
                return normalized;
        }
        catch { }
    }
    return null;
}
function normalizePayload(payload, fallbackModel, source) {
    const row = Array.isArray(payload?.models)
        ? payload.models.find((candidate) => String(candidate?.id || candidate?.model || candidate?.name || '') === fallbackModel) || payload.models[0]
        : payload?.model_metadata || payload?.metadata || payload;
    const efforts = normalizeAdvertisedEfforts(row?.advertised_efforts || row?.advertisedEfforts || row?.reasoning_efforts || row?.reasoningEfforts || payload?.advertised_efforts);
    return metadata(String(row?.model || row?.id || row?.name || fallbackModel), efforts, row?.default_effort || row?.defaultEffort || payload?.default_effort || 'medium', source, efforts.length ? [] : ['codex_model_metadata_efforts_missing']);
}
function metadata(model, efforts, defaultEffort, source, blockers) {
    const advertised = normalizeAdvertisedEfforts(efforts);
    const defaultValue = advertised.includes(defaultEffort) ? defaultEffort : advertised.includes('medium') ? 'medium' : advertised[0] || 'medium';
    return {
        schema: 'sks.codex-model-metadata.v1',
        model,
        advertised_efforts: advertised,
        default_effort: defaultValue,
        source,
        blockers
    };
}
function normalizeAdvertisedEfforts(value) {
    const rows = Array.isArray(value) ? value : String(value || '').split(',');
    const seen = new Set();
    const out = [];
    for (const row of rows) {
        const effort = String(row || '').trim().toLowerCase();
        if (!effort || seen.has(effort))
            continue;
        seen.add(effort);
        out.push(effort);
    }
    return out;
}
//# sourceMappingURL=codex-model-metadata.js.map