import fs from 'fs';
import path from 'path';
export function readMcpJson(projectDir) {
    const mcpPath = path.join(projectDir, '.mcp.json');
    if (!fs.existsSync(mcpPath)) {
        return { mcpServers: {} };
    }
    try {
        return JSON.parse(fs.readFileSync(mcpPath, 'utf-8'));
    }
    catch {
        return { mcpServers: {} };
    }
}
export function writeMcpConfig(projectDir, def, authValues, resolvedCommand) {
    const mcpJson = readMcpJson(projectDir);
    const command = resolvedCommand ?? def.server.command;
    if (!command)
        return;
    mcpJson.mcpServers[def.id] = {
        command,
        args: def.server.args,
        env: { ...def.server.env },
    };
    fs.writeFileSync(path.join(projectDir, '.mcp.json'), JSON.stringify(mcpJson, null, 2) + '\n');
    // Write env vars
    const envPath = path.join(projectDir, '.env');
    const examplePath = path.join(projectDir, '.env.example');
    let envContent = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf-8') : '';
    let exampleContent = fs.existsSync(examplePath) ? fs.readFileSync(examplePath, 'utf-8') : '';
    const mcpHeader = `\n# MCP: ${def.name}\n`;
    let envBlock = '';
    let exampleBlock = '';
    for (const auth of def.auth) {
        const value = authValues[auth.key] ?? '';
        if (!envContent.includes(`${auth.key}=`)) {
            envBlock += `${auth.key}=${value}\n`;
        }
        if (!exampleContent.includes(`${auth.key}=`)) {
            exampleBlock += `${auth.key}=\n`;
        }
    }
    if (envBlock) {
        envContent += mcpHeader + envBlock;
        fs.writeFileSync(envPath, envContent);
    }
    if (exampleBlock) {
        exampleContent += mcpHeader + exampleBlock;
        fs.writeFileSync(examplePath, exampleContent);
    }
}
export function removeMcpConfig(projectDir, mcpId) {
    const mcpJson = readMcpJson(projectDir);
    delete mcpJson.mcpServers[mcpId];
    fs.writeFileSync(path.join(projectDir, '.mcp.json'), JSON.stringify(mcpJson, null, 2) + '\n');
}
