"use strict";
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.ensureCodexCliproxyProviderConfig = exports.isCcsxpCliproxyShortcut = exports.buildCodexCliproxyProviderBaseUrl = exports.CODEX_CLIPROXY_PROVIDER_NAME = exports.CODEX_CLIPROXY_PROVIDER_ENV_KEY = exports.CODEX_CLIPROXY_PROVIDER_ID = exports.CCSXP_CLIPROXY_SHORTCUT_ENV = void 0;
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const helpers_1 = require("../utils/helpers");
const compatible_cli_toml_file_service_1 = require("../web-server/services/compatible-cli-toml-file-service");
const model_catalog_1 = require("../cliproxy/model-catalog");
const model_id_normalizer_1 = require("../cliproxy/ai-providers/model-id-normalizer");
exports.CCSXP_CLIPROXY_SHORTCUT_ENV = 'CCSXP_CLIPROXY_SHORTCUT';
exports.CODEX_CLIPROXY_PROVIDER_ID = 'cliproxy';
exports.CODEX_CLIPROXY_PROVIDER_ENV_KEY = 'CLIPROXY_API_KEY';
exports.CODEX_CLIPROXY_PROVIDER_NAME = 'CLIProxy Codex';
const CODEX_FAST_SERVICE_TIER = 'priority';
function resolveCodexConfigPath(env = process.env) {
    const baseDir = path.resolve(env.CODEX_HOME ? (0, helpers_1.expandPath)(env.CODEX_HOME) : path.join(os.homedir(), '.codex'));
    const displayBase = env.CODEX_HOME ? '$CODEX_HOME' : '~/.codex';
    return {
        configPath: path.join(baseDir, 'config.toml'),
        displayPath: `${displayBase}/config.toml`,
    };
}
function buildCodexCliproxyProviderBaseUrl(port) {
    return `http://127.0.0.1:${port}/api/provider/codex`;
}
exports.buildCodexCliproxyProviderBaseUrl = buildCodexCliproxyProviderBaseUrl;
function isCcsxpCliproxyShortcut(env = process.env) {
    return env[exports.CCSXP_CLIPROXY_SHORTCUT_ENV] === '1';
}
exports.isCcsxpCliproxyShortcut = isCcsxpCliproxyShortcut;
function asObject(value) {
    return typeof value === 'object' && value !== null && !Array.isArray(value)
        ? value
        : null;
}
function isValidCodexCliproxyBaseUrl(value) {
    if (typeof value !== 'string')
        return false;
    const trimmed = value.trim();
    if (!trimmed)
        return false;
    try {
        const url = new URL(trimmed);
        return url.protocol === 'http:' || url.protocol === 'https:';
    }
    catch {
        return false;
    }
}
function resolveProviderEnvKey(provider) {
    const envKey = provider?.env_key;
    if (typeof envKey === 'string' && envKey.trim()) {
        return envKey.trim();
    }
    return exports.CODEX_CLIPROXY_PROVIDER_ENV_KEY;
}
function isProviderReady(provider, envKey) {
    return (provider.name === exports.CODEX_CLIPROXY_PROVIDER_NAME &&
        isValidCodexCliproxyBaseUrl(provider.base_url) &&
        provider.env_key === envKey &&
        provider.wire_api === 'responses' &&
        provider.requires_openai_auth === false &&
        provider.supports_websockets === false);
}
function buildProviderConfig(baseUrl, envKey) {
    return {
        name: exports.CODEX_CLIPROXY_PROVIDER_NAME,
        base_url: baseUrl,
        env_key: envKey,
        wire_api: 'responses',
        requires_openai_auth: false,
        supports_websockets: false,
    };
}
function resolveProviderBaseUrl(provider, fallbackBaseUrl) {
    const baseUrl = provider.base_url;
    if (isValidCodexCliproxyBaseUrl(baseUrl)) {
        return baseUrl.trim();
    }
    return fallbackBaseUrl;
}
function appendProviderBlock(rawText, baseUrl) {
    const prefix = rawText.trimEnd();
    const providerBlock = (0, compatible_cli_toml_file_service_1.stringifyTomlObject)({
        model_providers: {
            [exports.CODEX_CLIPROXY_PROVIDER_ID]: buildProviderConfig(baseUrl, exports.CODEX_CLIPROXY_PROVIDER_ENV_KEY),
        },
    }).trimEnd();
    return prefix ? `${prefix}\n\n${providerBlock}\n` : `${providerBlock}\n`;
}
function normalizeTopLevelCodexModelAlias(config) {
    const model = config.model;
    if (typeof model !== 'string')
        return false;
    const parsed = (0, model_id_normalizer_1.parseCodexModelTuningAlias)(model);
    if (!parsed || (!parsed.effort && !parsed.serviceTier))
        return false;
    if (!parsed.baseModel || (0, model_catalog_1.getModelMaxLevel)('codex', parsed.baseModel) === undefined)
        return false;
    config.model = parsed.baseModel;
    if (parsed.effort)
        config.model_reasoning_effort = parsed.effort;
    if (parsed.serviceTier)
        config.service_tier = CODEX_FAST_SERVICE_TIER;
    return true;
}
async function ensureCodexCliproxyProviderConfig(port, env = process.env) {
    const { configPath, displayPath } = resolveCodexConfigPath(env);
    const fileProbe = await (0, compatible_cli_toml_file_service_1.probeTomlObjectFile)(configPath, 'Codex user config', displayPath);
    if (fileProbe.diagnostics.readError) {
        throw new Error(`Cannot repair ${displayPath}: ${fileProbe.diagnostics.readError}`);
    }
    if (fileProbe.diagnostics.parseError) {
        throw new Error(`Cannot repair ${displayPath}: ${fileProbe.diagnostics.parseError}`);
    }
    const config = fileProbe.config ?? {};
    const modelProvidersValue = config.model_providers;
    const providers = asObject(modelProvidersValue);
    const expectedBaseUrl = buildCodexCliproxyProviderBaseUrl(port);
    const normalizedModelAlias = normalizeTopLevelCodexModelAlias(config);
    if (modelProvidersValue !== undefined && !providers) {
        throw new Error(`Cannot repair ${displayPath}: [model_providers] must be a table.`);
    }
    if (!providers || !Object.prototype.hasOwnProperty.call(providers, exports.CODEX_CLIPROXY_PROVIDER_ID)) {
        await (0, compatible_cli_toml_file_service_1.writeTomlFileAtomic)({
            filePath: configPath,
            rawText: normalizedModelAlias
                ? (0, compatible_cli_toml_file_service_1.stringifyTomlObject)({
                    ...config,
                    model_providers: {
                        ...(providers ?? {}),
                        [exports.CODEX_CLIPROXY_PROVIDER_ID]: buildProviderConfig(expectedBaseUrl, exports.CODEX_CLIPROXY_PROVIDER_ENV_KEY),
                    },
                })
                : appendProviderBlock(fileProbe.rawText, expectedBaseUrl),
            expectedMtime: fileProbe.diagnostics.mtimeMs ?? undefined,
            fileLabel: 'config.toml',
        });
        return { changed: true, configPath, displayPath, envKey: exports.CODEX_CLIPROXY_PROVIDER_ENV_KEY };
    }
    const currentProvider = asObject(providers[exports.CODEX_CLIPROXY_PROVIDER_ID]);
    if (!currentProvider) {
        throw new Error(`Cannot repair ${displayPath}: [model_providers.${exports.CODEX_CLIPROXY_PROVIDER_ID}] must be a table.`);
    }
    const envKey = resolveProviderEnvKey(currentProvider);
    const providerReady = isProviderReady(currentProvider, envKey);
    if (!providerReady) {
        providers[exports.CODEX_CLIPROXY_PROVIDER_ID] = {
            ...currentProvider,
            ...buildProviderConfig(resolveProviderBaseUrl(currentProvider, expectedBaseUrl), envKey),
        };
    }
    if (providerReady && !normalizedModelAlias) {
        return { changed: false, configPath, displayPath, envKey };
    }
    await (0, compatible_cli_toml_file_service_1.writeTomlFileAtomic)({
        filePath: configPath,
        rawText: (0, compatible_cli_toml_file_service_1.stringifyTomlObject)(config),
        expectedMtime: fileProbe.diagnostics.mtimeMs ?? undefined,
        fileLabel: 'config.toml',
    });
    return { changed: true, configPath, displayPath, envKey };
}
exports.ensureCodexCliproxyProviderConfig = ensureCodexCliproxyProviderConfig;
//# sourceMappingURL=codex-cliproxy-provider-config.js.map