// packages/plugin-awf/src/commands/mcp-writers.ts
// Config file writers for MCP configuration, extracted from mcp.ts
import * as fs from "node:fs";
// ═══════════════════════════════════════════════════════════════════════════
// CONFIG WRITERS
// ═══════════════════════════════════════════════════════════════════════════
export async function writeJSONConfig(configPath, mcpKeyName, serverName, serverConfig, force) {
    let existingConfig = {};
    if (fs.existsSync(configPath)) {
        try {
            const content = fs.readFileSync(configPath, "utf-8");
            existingConfig = JSON.parse(content);
        }
        catch {
            if (!force) {
                return { success: false, error: "Invalid existing config (use --force)" };
            }
        }
    }
    const mcpServers = existingConfig[mcpKeyName] || {};
    // Check if already exists
    if (mcpServers[serverName] && !force) {
        return { success: false, error: "Already configured (use --force)" };
    }
    mcpServers[serverName] = serverConfig;
    existingConfig[mcpKeyName] = mcpServers;
    fs.writeFileSync(configPath, JSON.stringify(existingConfig, null, 2));
    return { success: true, configPath };
}
export async function writeYAMLConfig(configPath, mcpKeyName, serverName, serverConfig, force) {
    // Dynamic import for YAML
    const YAML = await import("yaml");
    let existingConfig = {};
    if (fs.existsSync(configPath)) {
        try {
            const content = fs.readFileSync(configPath, "utf-8");
            existingConfig = YAML.parse(content) || {};
        }
        catch {
            if (!force) {
                return { success: false, error: "Invalid existing YAML config (use --force)" };
            }
        }
    }
    // Continue.dev uses ARRAY format for mcpServers, not object!
    // Format: mcpServers: [{ name: "server-name", command: "...", args: [...], env: {...} }]
    let mcpServers = existingConfig[mcpKeyName] || [];
    // Ensure it's an array (backwards compatibility)
    if (!Array.isArray(mcpServers)) {
        mcpServers = [];
    }
    // Check if server already exists by name
    const existingIndex = mcpServers.findIndex(s => s.name === serverName);
    if (existingIndex !== -1 && !force) {
        return { success: false, error: "Already configured (use --force)" };
    }
    // Build Continue.dev format server entry — only standard MCP keys
    const { command, args, env } = serverConfig;
    const continueServerEntry = {
        name: serverName,
        ...(command !== undefined && { command }),
        ...(args !== undefined && { args }),
        ...(env !== undefined && { env }),
    };
    if (existingIndex !== -1) {
        // Update existing
        mcpServers[existingIndex] = continueServerEntry;
    }
    else {
        // Add new
        mcpServers.push(continueServerEntry);
    }
    existingConfig[mcpKeyName] = mcpServers;
    fs.writeFileSync(configPath, YAML.stringify(existingConfig));
    return { success: true, configPath };
}
/**
 * Write MCP config in TOML format (Codex CLI).
 * Uses simple string template — no TOML parser dependency needed.
 *
 * Output format per OpenAI docs:
 * ```toml
 * [mcp_servers.domyh-hsa]
 * command = "npx"
 * args = ["-y", "-p", "@nockdev/hsa@latest", "nock-hsa"]
 *
 * [mcp_servers.domyh-hsa.env]
 * HSA_PROJECT_PATH = "${workspaceFolder}"
 * HSA_MAX_TOKENS = "8000"
 * ```
 */
export async function writeTOMLConfig(configPath, mcpKeyName, serverName, serverConfig, force) {
    let existingContent = "";
    if (fs.existsSync(configPath)) {
        existingContent = fs.readFileSync(configPath, "utf-8");
        // Check if server section already exists
        const sectionHeader = `[${mcpKeyName}.${serverName}]`;
        if (existingContent.includes(sectionHeader) && !force) {
            return { success: false, error: "Already configured (use --force)" };
        }
    }
    // Build TOML section
    const tomlSection = buildTOMLSection(mcpKeyName, serverName, serverConfig);
    if (existingContent) {
        // Remove existing section if present (force mode)
        const sectionRegex = new RegExp(`\\[${escapeRegex(mcpKeyName)}\\.${escapeRegex(serverName)}\\][\\s\\S]*?(?=\\n\\[|$)`, "g");
        let cleaned = existingContent.replace(sectionRegex, "").trim();
        // Also remove env sub-section
        const envRegex = new RegExp(`\\[${escapeRegex(mcpKeyName)}\\.${escapeRegex(serverName)}\\.env\\][\\s\\S]*?(?=\\n\\[|$)`, "g");
        cleaned = cleaned.replace(envRegex, "").trim();
        existingContent = cleaned + "\n\n" + tomlSection;
    }
    else {
        existingContent = tomlSection;
    }
    fs.writeFileSync(configPath, existingContent.trim() + "\n");
    return { success: true, configPath };
}
function buildTOMLSection(mcpKeyName, serverName, config) {
    const lines = [];
    const sectionPrefix = `${mcpKeyName}.${serverName}`;
    lines.push(`[${sectionPrefix}]`);
    // Add simple key-value pairs
    if (config.command) {
        lines.push(`command = "${config.command}"`);
    }
    // description removed — non-standard MCP key
    if (Array.isArray(config.args)) {
        // TOML: Use single-quoted literal strings for args to avoid backslash
        // escape issues on Windows (e.g., C:\Users → \U is unicode escape in TOML)
        const argsStr = config.args.map((a) => `'${a}'`).join(", ");
        lines.push(`args = [${argsStr}]`);
    }
    // Add env sub-section
    if (config.env && typeof config.env === "object") {
        lines.push("");
        lines.push(`[${sectionPrefix}.env]`);
        for (const [key, value] of Object.entries(config.env)) {
            lines.push(`${key} = "${value}"`);
        }
    }
    return lines.join("\n");
}
function escapeRegex(str) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
