"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMcpTargets = getMcpTargets;
exports.applyMcpTarget = applyMcpTarget;
exports.readConfigFile = readConfigFile;
exports.writeMcpConfig = writeMcpConfig;
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const LEGACY_CELL_KEYS = ['cell', 'fivo-cell', 'FIVO-Cell', 'Cell', 'fivo_cell'];
function getMcpTargets(homedir) {
    return [
        {
            name: 'Cursor',
            configPath: path.join(homedir, '.cursor', 'mcp.json'),
            format: 'json',
            cellKey: 'fivo-cell',
            url: 'http://localhost:9876/mcp',
            description: '~/.cursor/mcp.json',
            buildPayload: (url) => ({ url }),
            containerKey: 'mcpServers',
        },
        {
            name: 'Gemini CLI',
            configPath: path.join(homedir, '.gemini', 'settings.json'),
            format: 'json',
            cellKey: 'fivo-cell',
            url: 'http://localhost:9876/mcp',
            description: '~/.gemini/settings.json',
            buildPayload: (url) => ({ url }),
            containerKey: 'mcpServers',
        },
        {
            name: 'Antigravity',
            configPath: path.join(homedir, '.gemini', 'config', 'mcp_config.json'),
            format: 'json',
            cellKey: 'fivo-cell',
            url: 'http://localhost:9876/mcp',
            description: '~/.gemini/config/mcp_config.json',
            buildPayload: (url) => ({ serverUrl: url }),
            containerKey: 'mcpServers',
        },
        {
            name: 'Codex',
            configPath: path.join(homedir, '.codex', 'config.json'),
            format: 'json',
            cellKey: 'fivo-cell',
            url: 'http://localhost:9876/mcp',
            description: '~/.codex/config.json',
            buildPayload: (url) => ({ url }),
            containerKey: 'mcp.servers',
        },
        {
            name: 'OpenCode',
            configPath: path.join(homedir, '.config', 'opencode', 'opencode.jsonc'),
            format: 'jsonc',
            cellKey: 'cell',
            url: 'http://localhost:9876/mcp',
            description: '~/.config/opencode/opencode.jsonc',
            buildPayload: (url) => ({
                type: 'remote',
                url,
                enabled: true,
            }),
            containerKey: 'mcp',
        },
    ];
}
function applyMcpTarget(t, cfg) {
    let container;
    if (t.containerKey === 'mcp.servers') {
        const mcp = cfg.mcp || {};
        container = mcp.servers || {};
    }
    else {
        container = cfg[t.containerKey] || {};
    }
    for (const k of LEGACY_CELL_KEYS) {
        if (k !== t.cellKey) {
            delete container[k];
        }
    }
    container[t.cellKey] = t.buildPayload(t.url);
    if (t.containerKey === 'mcp.servers') {
        const mcp = cfg.mcp || {};
        mcp.servers = container;
        cfg.mcp = mcp;
        delete cfg.mcpServers;
    }
    else {
        cfg[t.containerKey] = container;
    }
    return cfg;
}
function readConfigFile(filePath, format) {
    const raw = fs.readFileSync(filePath, 'utf8');
    const stripped = format === 'jsonc'
        ? raw.replace(/^\s*\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '')
        : raw;
    return JSON.parse(stripped);
}
function writeMcpConfig(homedir = os.homedir()) {
    const targets = getMcpTargets(homedir);
    const written = [];
    const skipped = [];
    for (const t of targets) {
        const dir = path.dirname(t.configPath);
        let cfg = {};
        if (fs.existsSync(t.configPath)) {
            try {
                cfg = readConfigFile(t.configPath, t.format);
            }
            catch (err) {
                const msg = err instanceof Error ? err.message : String(err);
                skipped.push({ name: t.name, reason: msg });
                continue;
            }
        }
        cfg = applyMcpTarget(t, cfg);
        try {
            fs.mkdirSync(dir, { recursive: true });
            fs.writeFileSync(t.configPath, JSON.stringify(cfg, null, 2) + '\n', 'utf8');
            written.push(t.configPath);
        }
        catch (err) {
            const msg = err instanceof Error ? err.message : String(err);
            skipped.push({ name: t.name, reason: msg });
        }
    }
    return { written, skipped };
}
//# sourceMappingURL=mcp-config.js.map