"use strict";
/**
 * Local Config Sync
 *
 * Syncs CCS API profiles to the local CLIProxy config.yaml.
 * Uses section-based replacement to preserve comments and formatting.
 */
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.getLocalSyncStatus = exports.syncToLocalConfig = void 0;
const fs = __importStar(require("fs"));
const yaml = __importStar(require("js-yaml"));
const config_generator_1 = require("../config/config-generator");
const profile_mapper_1 = require("./profile-mapper");
/**
 * Sync profiles to local CLIProxy config.yaml.
 * Replaces only the claude-api-key section, preserving all other content.
 *
 * @returns Object with success status and synced count
 */
function syncToLocalConfig() {
    const configPath = (0, config_generator_1.getCliproxyConfigPath)();
    try {
        // Generate payload from CCS profiles
        const payload = (0, profile_mapper_1.generateSyncPayload)();
        if (payload.length === 0) {
            return {
                success: true,
                syncedCount: 0,
                configPath,
            };
        }
        // Read existing config
        if (!fs.existsSync(configPath)) {
            return {
                success: false,
                syncedCount: 0,
                configPath,
                error: 'CLIProxy config not found. Run ccs doctor to generate.',
            };
        }
        let configContent;
        try {
            configContent = fs.readFileSync(configPath, 'utf8');
        }
        catch (error) {
            if (error.code === 'ENOENT') {
                return {
                    success: false,
                    syncedCount: 0,
                    configPath,
                    error: 'CLIProxy config deleted during sync. Run ccs doctor to regenerate.',
                };
            }
            throw error;
        }
        // Transform payload to config format
        const claudeApiKeys = payload.map(transformToConfigFormat);
        // Generate YAML for the claude-api-key section only
        const newSection = yaml.dump({ 'claude-api-key': claudeApiKeys }, {
            indent: 2,
            lineWidth: -1,
            quotingType: "'",
            forceQuotes: false,
        });
        // Replace section in original content (preserves comments/formatting)
        const newContent = replaceSectionInYaml(configContent, 'claude-api-key', newSection);
        // Atomic write with cleanup on failure
        const tempPath = configPath + '.tmp';
        try {
            fs.writeFileSync(tempPath, newContent, { mode: 0o600 });
            fs.renameSync(tempPath, configPath);
        }
        catch (writeError) {
            // Clean up temp file if it exists
            if (fs.existsSync(tempPath)) {
                try {
                    fs.unlinkSync(tempPath);
                }
                catch {
                    // Ignore cleanup errors
                }
            }
            throw writeError;
        }
        return {
            success: true,
            syncedCount: payload.length,
            configPath,
        };
    }
    catch (error) {
        return {
            success: false,
            syncedCount: 0,
            configPath,
            error: error.message,
        };
    }
}
exports.syncToLocalConfig = syncToLocalConfig;
/**
 * Replace a top-level section in YAML content while preserving rest of file.
 * Finds the section by key name and replaces it (including nested content).
 */
function replaceSectionInYaml(content, sectionKey, newSection) {
    const lines = content.split('\n');
    const result = [];
    let inSection = false;
    let sectionFound = false;
    for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        const trimmed = line.trimStart();
        // Check if this is the start of our target section
        if (trimmed.startsWith(`${sectionKey}:`)) {
            inSection = true;
            sectionFound = true;
            // Insert new section here
            result.push(newSection.trimEnd());
            continue;
        }
        // If we're in the section, skip lines until we hit another top-level key
        if (inSection) {
            // Top-level key: starts at column 0, valid YAML key format (word chars + hyphens)
            // Must match pattern like "key:", "my-key:", "key_name:" but not comments or strings
            const isTopLevelKey = line.length > 0 &&
                !line.startsWith(' ') &&
                !line.startsWith('\t') &&
                !line.startsWith('#') &&
                /^[a-zA-Z_][a-zA-Z0-9_-]*\s*:/.test(line);
            if (isTopLevelKey) {
                // We've exited the section, resume normal processing
                inSection = false;
                result.push(line);
            }
            // Otherwise skip this line (part of old section)
            continue;
        }
        result.push(line);
    }
    // If section wasn't found, append it at the end
    if (!sectionFound) {
        result.push('');
        result.push(newSection.trimEnd());
    }
    return result.join('\n');
}
/**
 * Transform ClaudeKey to config.yaml format.
 * The config format uses slightly different field names.
 */
function transformToConfigFormat(key) {
    const entry = {
        'api-key': key['api-key'],
    };
    if (key['base-url']) {
        entry['base-url'] = key['base-url'];
    }
    // Add empty proxy-url (required by CLIProxyAPI)
    entry['proxy-url'] = '';
    // Use model name directly (no alias mapping)
    if (key.models && key.models.length > 0) {
        entry.models = key.models.map((m) => ({
            name: m.name,
            alias: '',
        }));
    }
    // Note: prefix is not used in local config - it's for remote routing only
    return entry;
}
/**
 * Get local sync status.
 */
function getLocalSyncStatus() {
    const configPath = (0, config_generator_1.getCliproxyConfigPath)();
    let currentKeyCount = 0;
    if (fs.existsSync(configPath)) {
        try {
            const content = fs.readFileSync(configPath, 'utf8');
            const config = yaml.load(content);
            if (config && typeof config === 'object') {
                const keys = config['claude-api-key'];
                if (Array.isArray(keys)) {
                    currentKeyCount = keys.length;
                }
            }
        }
        catch {
            // Ignore parse errors
        }
    }
    const payload = (0, profile_mapper_1.generateSyncPayload)();
    return {
        configExists: fs.existsSync(configPath),
        configPath,
        currentKeyCount,
        syncableProfileCount: payload.length,
    };
}
exports.getLocalSyncStatus = getLocalSyncStatus;
//# sourceMappingURL=local-config-sync.js.map