"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ensureManagedModelPrefixes = void 0;
const cliproxy_model_routing_1 = require("../../shared/cliproxy-model-routing");
const proxy_target_resolver_1 = require("../proxy/proxy-target-resolver");
const provider_capabilities_1 = require("../provider-capabilities");
const MANAGED_PREFIX_REQUEST_TIMEOUT_MS = 3000;
function normalizeProvider(record) {
    const providerName = record.provider?.trim() || record.type?.trim() || '';
    return providerName ? (0, provider_capabilities_1.mapExternalProviderName)(providerName) : null;
}
async function fetchManagementEndpoint(path, init = {}) {
    const target = (0, proxy_target_resolver_1.getProxyTarget)();
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), MANAGED_PREFIX_REQUEST_TIMEOUT_MS);
    try {
        return await fetch((0, proxy_target_resolver_1.buildProxyUrl)(target, path), {
            ...init,
            headers: (0, proxy_target_resolver_1.buildManagementHeaders)(target, init.headers),
            signal: controller.signal,
        });
    }
    finally {
        clearTimeout(timeoutId);
    }
}
async function listAuthFiles() {
    const response = await fetchManagementEndpoint('/v0/management/auth-files');
    if (!response.ok) {
        throw new Error(`auth file listing failed with status ${response.status}`);
    }
    const data = (await response.json());
    return Array.isArray(data.files) ? data.files : [];
}
async function patchAuthFilePrefix(name, prefix) {
    const response = await fetchManagementEndpoint('/v0/management/auth-files/fields', {
        method: 'PATCH',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name, prefix }),
    });
    if (!response.ok) {
        throw new Error(`auth file prefix patch failed for ${name} with status ${response.status}`);
    }
}
async function readAuthFileMetadata(name) {
    const response = await fetchManagementEndpoint(`/v0/management/auth-files/download?name=${encodeURIComponent(name)}`);
    if (!response.ok) {
        throw new Error(`auth file download failed for ${name} with status ${response.status}`);
    }
    const content = await response.text();
    try {
        const parsed = JSON.parse(content);
        const providerName = typeof parsed.provider === 'string'
            ? parsed.provider
            : typeof parsed.type === 'string'
                ? parsed.type
                : '';
        return {
            prefix: typeof parsed.prefix === 'string' ? parsed.prefix.trim() : null,
            provider: providerName ? (0, provider_capabilities_1.mapExternalProviderName)(providerName) : null,
        };
    }
    catch {
        return { prefix: null, provider: null };
    }
}
async function ensureManagedModelPrefixes(providers) {
    const allowedProviders = new Set((providers ?? [])
        .map((provider) => provider.trim())
        .filter((provider) => (0, cliproxy_model_routing_1.getManagedModelPrefix)(provider)));
    if (providers && allowedProviders.size === 0) {
        return { checked: 0, updated: 0 };
    }
    const files = await listAuthFiles();
    let checked = 0;
    let updated = 0;
    for (const record of files) {
        if ((record.account_type || '').trim().toLowerCase() !== 'oauth') {
            continue;
        }
        const provider = normalizeProvider(record);
        if (!provider) {
            continue;
        }
        if (allowedProviders.size > 0 && !allowedProviders.has(provider)) {
            continue;
        }
        const prefix = (0, cliproxy_model_routing_1.getManagedModelPrefix)(provider);
        if (!prefix) {
            continue;
        }
        try {
            checked += 1;
            const { prefix: currentPrefix, provider: fileProvider } = await readAuthFileMetadata(record.name);
            if (fileProvider !== provider) {
                continue;
            }
            if (currentPrefix === prefix) {
                continue;
            }
            if (currentPrefix && currentPrefix !== prefix) {
                continue;
            }
            await patchAuthFilePrefix(record.name, prefix);
            updated += 1;
        }
        catch {
            // Best-effort repair: skip files that cannot be read or patched.
        }
    }
    return { checked, updated };
}
exports.ensureManagedModelPrefixes = ensureManagedModelPrefixes;
//# sourceMappingURL=managed-model-prefixes.js.map