"use strict";
/**
 * Copilot Settings Routes - Settings editor and raw settings for GitHub Copilot
 */
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 });
const express_1 = require("express");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const copilot_model_normalizer_1 = require("../../copilot/copilot-model-normalizer");
const unified_config_types_1 = require("../../config/unified-config-types");
const config_loader_facade_1 = require("../../config/config-loader-facade");
const router = (0, express_1.Router)();
function serializeSettings(settings) {
    return JSON.stringify(settings, null, 2) + '\n';
}
function writeSettingsFile(settingsPath, settings, previousContent) {
    const nextContent = serializeSettings(settings);
    if (previousContent === nextContent)
        return;
    const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
    fs.writeFileSync(tempPath, nextContent);
    fs.renameSync(tempPath, settingsPath);
}
function restoreSettingsFile(settingsPath, previousContent, existedBefore) {
    if (!existedBefore) {
        if (fs.existsSync(settingsPath)) {
            fs.unlinkSync(settingsPath);
        }
        return;
    }
    const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.restore.tmp`;
    fs.writeFileSync(tempPath, previousContent ?? '');
    fs.renameSync(tempPath, settingsPath);
}
function buildDefaultSettings(copilotConfig) {
    return {
        env: {
            ANTHROPIC_BASE_URL: `http://127.0.0.1:${copilotConfig.port}`,
            ANTHROPIC_AUTH_TOKEN: 'copilot-managed',
            ANTHROPIC_MODEL: copilotConfig.model,
            ANTHROPIC_DEFAULT_OPUS_MODEL: copilotConfig.opus_model || copilotConfig.model,
            ANTHROPIC_DEFAULT_SONNET_MODEL: copilotConfig.sonnet_model || copilotConfig.model,
            ANTHROPIC_DEFAULT_HAIKU_MODEL: copilotConfig.haiku_model || copilotConfig.model,
            ANTHROPIC_SMALL_FAST_MODEL: copilotConfig.haiku_model || copilotConfig.model,
        },
    };
}
/**
 * GET /api/copilot/settings/raw - Get raw copilot.settings.json
 * Returns the raw JSON content for editing in the code editor
 */
router.get('/raw', (_req, res) => {
    try {
        const settingsPath = path.join((0, config_loader_facade_1.getCcsDir)(), 'copilot.settings.json');
        const config = (0, config_loader_facade_1.loadOrCreateUnifiedConfig)();
        const configResult = (0, copilot_model_normalizer_1.normalizeCopilotConfigWithWarnings)(config.copilot ?? unified_config_types_1.DEFAULT_COPILOT_CONFIG);
        if (!fs.existsSync(settingsPath)) {
            const defaultSettings = (0, copilot_model_normalizer_1.normalizeCopilotSettingsWithWarnings)(buildDefaultSettings(configResult.config), configResult.config);
            res.json({
                settings: defaultSettings.settings,
                effectiveSettings: defaultSettings.settings,
                mtime: Date.now(),
                path: `~/.ccs/copilot.settings.json`,
                exists: false,
                warnings: defaultSettings.warnings,
            });
            return;
        }
        const content = fs.readFileSync(settingsPath, 'utf-8');
        const rawSettings = JSON.parse(content);
        const settingsResult = (0, copilot_model_normalizer_1.normalizeCopilotSettingsWithWarnings)(rawSettings, configResult.config);
        const stat = fs.statSync(settingsPath);
        res.json({
            settings: rawSettings,
            effectiveSettings: settingsResult.settings,
            mtime: stat.mtimeMs,
            path: `~/.ccs/copilot.settings.json`,
            exists: true,
            warnings: settingsResult.warnings,
        });
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
/**
 * PUT /api/copilot/settings/raw - Save raw copilot.settings.json
 * Saves the raw JSON content from the code editor
 */
router.put('/raw', (req, res) => {
    try {
        const { settings, expectedMtime } = req.body;
        const settingsPath = path.join((0, config_loader_facade_1.getCcsDir)(), 'copilot.settings.json');
        if (!settings || typeof settings !== 'object' || Array.isArray(settings)) {
            res.status(400).json({ error: 'settings must be a JSON object' });
            return;
        }
        const currentConfig = (0, config_loader_facade_1.loadOrCreateUnifiedConfig)();
        const configResult = (0, copilot_model_normalizer_1.normalizeCopilotConfigWithWarnings)(currentConfig.copilot ?? unified_config_types_1.DEFAULT_COPILOT_CONFIG);
        // Check for conflict if file exists and expectedMtime provided
        if (fs.existsSync(settingsPath) && expectedMtime) {
            const stat = fs.statSync(settingsPath);
            if (Math.abs(stat.mtimeMs - expectedMtime) > 1000) {
                res.status(409).json({ error: 'File modified externally', mtime: stat.mtimeMs });
                return;
            }
        }
        const settingsResult = (0, copilot_model_normalizer_1.normalizeCopilotSettingsWithWarnings)(settings, configResult.config);
        const existedBefore = fs.existsSync(settingsPath);
        const previousContent = existedBefore ? fs.readFileSync(settingsPath, 'utf-8') : undefined;
        writeSettingsFile(settingsPath, settingsResult.settings, previousContent);
        try {
            (0, config_loader_facade_1.mutateConfig)((config) => {
                config.copilot = settingsResult.effectiveConfig;
            });
        }
        catch (error) {
            try {
                restoreSettingsFile(settingsPath, previousContent, existedBefore);
            }
            catch (rollbackError) {
                throw new Error(`Failed to sync unified config after writing Copilot settings: ${error.message}. Rollback also failed: ${rollbackError.message}`);
            }
            throw error;
        }
        const stat = fs.statSync(settingsPath);
        res.json({
            success: true,
            mtime: stat.mtimeMs,
            settings: settingsResult.settings,
            warnings: settingsResult.warnings,
        });
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
exports.default = router;
//# sourceMappingURL=copilot-settings-routes.js.map