"use strict";
/**
 * OpenAI Compatibility Layer Manager
 *
 * Manages OpenAI-compatible providers (OpenRouter, Together, etc.)
 * in CLIProxyAPI's config.yaml.
 */
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.TOGETHER_TEMPLATE = exports.OPENROUTER_TEMPLATE = exports.removeOpenAICompatProvider = exports.updateOpenAICompatProvider = exports.addOpenAICompatProvider = exports.getOpenAICompatProvider = exports.listOpenAICompatProviders = void 0;
const fs = __importStar(require("fs"));
const yaml = __importStar(require("js-yaml"));
const generator_1 = require("../config/generator");
const path_resolver_1 = require("../config/path-resolver");
const config_yaml_sections_1 = require("./config-yaml-sections");
/**
 * Load current config.yaml
 */
function loadConfig() {
    const configPath = (0, path_resolver_1.getCliproxyConfigPath)();
    if (!fs.existsSync(configPath)) {
        return {};
    }
    try {
        const content = fs.readFileSync(configPath, 'utf-8');
        return yaml.load(content) || {};
    }
    catch {
        return {};
    }
}
/**
 * Persist only the openai-compatibility section so the generated config header
 * and unrelated user-managed sections survive legacy writes.
 */
function saveConfig(config) {
    const configPath = (0, path_resolver_1.getCliproxyConfigPath)();
    if (!(0, generator_1.configExists)()) {
        (0, generator_1.regenerateConfig)();
    }
    const currentContent = fs.existsSync(configPath) ? fs.readFileSync(configPath, 'utf-8') : '';
    const sectionContent = config['openai-compatibility'] && config['openai-compatibility'].length > 0
        ? yaml.dump({ 'openai-compatibility': config['openai-compatibility'] }, {
            lineWidth: -1,
            quotingType: '"',
            forceQuotes: false,
        })
        : null;
    const nextContent = (0, config_yaml_sections_1.rewriteTopLevelYamlSection)(currentContent, 'openai-compatibility', sectionContent);
    const tempPath = `${configPath}.tmp`;
    fs.writeFileSync(tempPath, nextContent, { mode: 0o600 });
    fs.renameSync(tempPath, configPath);
}
/**
 * List all configured OpenAI-compatible providers
 */
function listOpenAICompatProviders() {
    const config = loadConfig();
    const providers = config['openai-compatibility'] || [];
    return providers.map((p) => ({
        name: p.name,
        baseUrl: p['base-url'],
        apiKey: p['api-key-entries']?.[0]?.['api-key'] || '',
        models: (p.models || []).map((m) => ({
            name: m.name,
            alias: m.alias,
        })),
    }));
}
exports.listOpenAICompatProviders = listOpenAICompatProviders;
/**
 * Get a specific provider by name
 */
function getOpenAICompatProvider(name) {
    const providers = listOpenAICompatProviders();
    return providers.find((p) => p.name === name) || null;
}
exports.getOpenAICompatProvider = getOpenAICompatProvider;
/**
 * Add a new OpenAI-compatible provider
 * @throws Error if provider with same name already exists
 */
function addOpenAICompatProvider(provider) {
    const config = loadConfig();
    // Initialize array if not exists
    if (!config['openai-compatibility']) {
        config['openai-compatibility'] = [];
    }
    // Check for duplicate
    const existing = config['openai-compatibility'].find((p) => p.name === provider.name);
    if (existing) {
        throw new Error(`Provider '${provider.name}' already exists`);
    }
    // Add new provider
    config['openai-compatibility'].push({
        name: provider.name,
        'base-url': provider.baseUrl,
        'api-key-entries': [{ 'api-key': provider.apiKey }],
        models: provider.models.map((m) => ({
            name: m.name,
            alias: m.alias,
        })),
    });
    saveConfig(config);
}
exports.addOpenAICompatProvider = addOpenAICompatProvider;
/**
 * Update an existing provider
 * @throws Error if provider doesn't exist
 */
function updateOpenAICompatProvider(name, updates) {
    const config = loadConfig();
    if (!config['openai-compatibility']) {
        throw new Error(`Provider '${name}' not found`);
    }
    const index = config['openai-compatibility'].findIndex((p) => p.name === name);
    if (index === -1) {
        throw new Error(`Provider '${name}' not found`);
    }
    const provider = config['openai-compatibility'][index];
    // Apply updates
    if (updates.baseUrl) {
        provider['base-url'] = updates.baseUrl;
    }
    if (updates.apiKey) {
        provider['api-key-entries'] = [{ 'api-key': updates.apiKey }];
    }
    if (updates.models) {
        provider.models = updates.models.map((m) => ({
            name: m.name,
            alias: m.alias,
        }));
    }
    if (updates.name && updates.name !== name) {
        provider.name = updates.name;
    }
    saveConfig(config);
}
exports.updateOpenAICompatProvider = updateOpenAICompatProvider;
/**
 * Remove a provider
 * @returns true if removed, false if not found
 */
function removeOpenAICompatProvider(name) {
    const config = loadConfig();
    if (!config['openai-compatibility']) {
        return false;
    }
    const index = config['openai-compatibility'].findIndex((p) => p.name === name);
    if (index === -1) {
        return false;
    }
    config['openai-compatibility'].splice(index, 1);
    // Remove empty array
    if (config['openai-compatibility'].length === 0) {
        delete config['openai-compatibility'];
    }
    saveConfig(config);
    return true;
}
exports.removeOpenAICompatProvider = removeOpenAICompatProvider;
/** Pre-configured OpenRouter template */
exports.OPENROUTER_TEMPLATE = {
    name: 'openrouter',
    baseUrl: 'https://openrouter.ai/api/v1',
    models: [
        { name: 'anthropic/claude-3.5-sonnet', alias: 'claude-sonnet' },
        { name: 'anthropic/claude-3-opus', alias: 'claude-opus' },
        { name: 'google/gemini-pro-1.5', alias: 'gemini-pro' },
    ],
};
/** Pre-configured Together template */
exports.TOGETHER_TEMPLATE = {
    name: 'together',
    baseUrl: 'https://api.together.xyz/v1',
    models: [
        { name: 'meta-llama/Llama-3-70b-chat-hf', alias: 'llama-70b' },
        { name: 'mistralai/Mixtral-8x7B-Instruct-v0.1', alias: 'mixtral' },
    ],
};
//# sourceMappingURL=openai-compat-manager.js.map