/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * MCP server configuration manager for the web console.
 *
 * Reads and manages MCP server configurations across multiple targets
 * (Cursor, Claude, VS Code, Windsurf). Provides CRUD operations on
 * the `mcpServers` object in each target's config file.
 */
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { ensureDir, writeFileAtomic } from './file-writer.js';
// ─── Helpers ────────────────────────────────────────────────────────────────
function detectTransport(config) {
    if (config.url)
        return 'http';
    return 'stdio';
}
function readJsonSafe(filePath, fallback) {
    if (!existsSync(filePath))
        return fallback;
    try {
        return JSON.parse(readFileSync(filePath, 'utf8'));
    }
    catch {
        return fallback;
    }
}
function writeJsonSafe(filePath, data) {
    const dir = join(filePath, '..');
    ensureDir(dir);
    writeFileAtomic(filePath, JSON.stringify(data, null, 2) + '\n');
}
// ─── Config Path Resolution ─────────────────────────────────────────────────
function getConfigPath(target, workspacePath) {
    const home = homedir();
    switch (target) {
        case 'cursor':
            return join(home, '.cursor', 'mcp.json');
        case 'claude':
            return join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
        case 'vscode':
            if (workspacePath && existsSync(join(workspacePath, '.vscode'))) {
                return join(workspacePath, '.vscode', 'mcp.json');
            }
            return join(home, '.vscode', 'mcp.json');
        case 'windsurf':
            return join(home, '.codeium', 'windsurf', 'mcp_config.json');
    }
}
// ─── Public API ─────────────────────────────────────────────────────────────
/**
 * List all MCP servers for a specific target.
 */
export function listServers(target, workspacePath) {
    const configPath = getConfigPath(target, workspacePath);
    const data = readJsonSafe(configPath, { mcpServers: {} });
    const servers = [];
    for (const [name, config] of Object.entries(data.mcpServers ?? {})) {
        servers.push({
            name,
            transport: detectTransport(config),
            config,
        });
    }
    return { target, path: configPath, servers };
}
/**
 * List MCP servers across all targets.
 */
export function listAllServers(workspacePath) {
    const targets = ['cursor', 'claude', 'vscode', 'windsurf'];
    return targets.map((t) => listServers(t, workspacePath));
}
/**
 * Add or update a server entry in a target config.
 */
export function addServer(target, name, config, workspacePath) {
    const configPath = getConfigPath(target, workspacePath);
    const data = readJsonSafe(configPath, { mcpServers: {} });
    if (!data.mcpServers)
        data.mcpServers = {};
    data.mcpServers[name] = config;
    writeJsonSafe(configPath, data);
    return { path: configPath };
}
/**
 * Remove a server entry from a target config.
 */
export function removeServer(target, name, workspacePath) {
    const configPath = getConfigPath(target, workspacePath);
    const data = readJsonSafe(configPath, { mcpServers: {} });
    if (!data.mcpServers || !(name in data.mcpServers)) {
        return { removed: false, path: configPath };
    }
    delete data.mcpServers[name];
    writeJsonSafe(configPath, data);
    return { removed: true, path: configPath };
}
/**
 * Install a known integration to one or more targets.
 */
export function installIntegration(integrationId, targets, config, workspacePath) {
    const installed = [];
    for (const target of targets) {
        addServer(target, integrationId, config, workspacePath);
        installed.push(target);
    }
    return { installed };
}
//# sourceMappingURL=mcp-manager.js.map