"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.writeFamilyEntries = exports.readFamilyEntries = exports.getAiProvidersSourceSummary = void 0;
const crypto_1 = require("crypto");
const fs = __importStar(require("fs"));
const yaml = __importStar(require("js-yaml"));
const config_generator_1 = require("../config/config-generator");
const proxy_target_resolver_1 = require("../proxy/proxy-target-resolver");
const management_api_client_1 = require("../management/management-api-client");
const config_yaml_sections_1 = require("./config-yaml-sections");
function createFamilyEntryId(family) {
    return `${family}-${(0, crypto_1.randomUUID)()}`;
}
function ensureStableEntryIds(family, entries) {
    const seenIds = new Set();
    let changed = false;
    const normalizedEntries = entries.map((entry) => {
        const rawId = entry.id;
        const normalizedId = typeof rawId === 'string' && rawId.trim().length > 0 ? rawId.trim() : null;
        const nextId = normalizedId && !seenIds.has(normalizedId) ? normalizedId : createFamilyEntryId(family);
        if (normalizedId !== nextId) {
            changed = true;
        }
        seenIds.add(nextId);
        return {
            ...entry,
            id: nextId,
        };
    });
    return { entries: normalizedEntries, changed };
}
function ensureLocalConfigPath() {
    if (!(0, config_generator_1.configExists)()) {
        (0, config_generator_1.regenerateConfig)();
    }
    return (0, config_generator_1.getCliproxyConfigPath)();
}
function readLocalConfig() {
    const configPath = ensureLocalConfigPath();
    if (!fs.existsSync(configPath)) {
        return {};
    }
    try {
        const content = fs.readFileSync(configPath, 'utf8');
        return yaml.load(content) || {};
    }
    catch {
        return {};
    }
}
function writeLocalFamilySection(family, entries) {
    const configPath = ensureLocalConfigPath();
    const content = fs.existsSync(configPath) ? fs.readFileSync(configPath, 'utf8') : '';
    const sectionYaml = entries.length > 0
        ? yaml.dump({ [family]: entries }, {
            indent: 2,
            lineWidth: -1,
            quotingType: "'",
            forceQuotes: false,
        })
        : null;
    const nextContent = (0, config_yaml_sections_1.rewriteTopLevelYamlSection)(content, family, sectionYaml);
    const tempPath = `${configPath}.tmp`;
    fs.writeFileSync(tempPath, nextContent, { mode: 0o600 });
    fs.renameSync(tempPath, configPath);
}
function getAiProvidersSourceSummary() {
    const target = (0, proxy_target_resolver_1.getProxyTarget)();
    const managementAuth = target.isRemote
        ? target.managementKey
            ? 'configured'
            : target.authToken
                ? 'fallback'
                : 'missing'
        : 'configured';
    return {
        mode: target.isRemote ? 'remote' : 'local',
        label: target.isRemote ? 'Remote CLIProxy' : 'Local CLIProxy',
        target: `${target.protocol}://${target.host}:${target.port}`,
        managementAuth,
    };
}
exports.getAiProvidersSourceSummary = getAiProvidersSourceSummary;
async function readFamilyEntries(family) {
    const target = (0, proxy_target_resolver_1.getProxyTarget)();
    if (!target.isRemote) {
        const config = readLocalConfig();
        const entries = (Array.isArray(config[family]) ? config[family] : []);
        const normalized = ensureStableEntryIds(family, entries);
        if (normalized.changed) {
            writeLocalFamilySection(family, normalized.entries);
        }
        return normalized.entries;
    }
    const client = (0, management_api_client_1.createManagementClient)({
        host: target.host,
        port: target.port,
        protocol: target.protocol,
        management_key: target.managementKey,
        auth_token: target.authToken,
    });
    const entries = (await client.getSection(family));
    const normalized = ensureStableEntryIds(family, Array.isArray(entries) ? entries : []);
    if (normalized.changed) {
        await client.putSection(family, normalized.entries);
    }
    return normalized.entries;
}
exports.readFamilyEntries = readFamilyEntries;
async function writeFamilyEntries(family, entries) {
    const normalized = ensureStableEntryIds(family, entries);
    const target = (0, proxy_target_resolver_1.getProxyTarget)();
    if (!target.isRemote) {
        writeLocalFamilySection(family, normalized.entries);
        return;
    }
    const client = (0, management_api_client_1.createManagementClient)({
        host: target.host,
        port: target.port,
        protocol: target.protocol,
        management_key: target.managementKey,
        auth_token: target.authToken,
    });
    await client.putSection(family, normalized.entries);
}
exports.writeFamilyEntries = writeFamilyEntries;
//# sourceMappingURL=config-store.js.map