/**
 * MCP config discovery — parallel sweep of 5 source paths.
 *
 * Sources:
 *   1. Claude Code: ~/.claude.json mcpServers
 *   2. Claude Desktop: OS-specific config path mcpServers
 *   3. Cursor: ~/.cursor/mcp.json mcpServers
 *   4. Windsurf: ~/.codeium/windsurf/mcp_config.json mcpServers
 *   5. Project .mcp.json from each world repo path in .olam/config.yaml
 */
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
function readJsonFile(filePath) {
    try {
        const raw = fs.readFileSync(filePath, 'utf-8');
        return JSON.parse(raw);
    }
    catch {
        return null;
    }
}
function extractMcpServers(obj, source, sourceLabel) {
    if (!obj || typeof obj !== 'object' || Array.isArray(obj))
        return [];
    const record = obj;
    const mcpServers = record['mcpServers'] ?? record['mcps'];
    if (!mcpServers || typeof mcpServers !== 'object' || Array.isArray(mcpServers))
        return [];
    const result = [];
    for (const [name, entry] of Object.entries(mcpServers)) {
        if (!entry || typeof entry !== 'object')
            continue;
        const command = entry.command;
        if (!command || typeof command !== 'string')
            continue;
        result.push({
            name,
            command,
            args: Array.isArray(entry.args) ? entry.args : [],
            env: entry.env && typeof entry.env === 'object' ? entry.env : undefined,
            source,
            sourceLabel,
        });
    }
    return result;
}
function getClaudeDesktopPath() {
    if (process.platform === 'darwin') {
        return path.join(os.homedir(), 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
    }
    if (process.platform === 'win32') {
        const appData = process.env['APPDATA'] ?? path.join(os.homedir(), 'AppData', 'Roaming');
        return path.join(appData, 'Claude', 'claude_desktop_config.json');
    }
    return path.join(os.homedir(), '.config', 'Claude', 'claude_desktop_config.json');
}
function getOlamRepoPaths() {
    const configPaths = [
        path.join(os.homedir(), '.olam', 'config.yaml'),
        path.join(process.cwd(), '.olam', 'config.yaml'),
    ];
    const paths = [];
    for (const configPath of configPaths) {
        if (!fs.existsSync(configPath))
            continue;
        try {
            const raw = fs.readFileSync(configPath, 'utf-8');
            const repoMatches = [...raw.matchAll(/path:\s*["']?([^\s"'\n]+)/g)];
            for (const m of repoMatches) {
                if (m[1])
                    paths.push(m[1]);
            }
        }
        catch { /* ignore */ }
    }
    return paths;
}
export async function discoverMcpSources(repoPaths) {
    const start = performance.now();
    const allEntries = [];
    const sources = [];
    const sourceDefs = [
        {
            path: path.join(os.homedir(), '.claude.json'),
            label: 'Claude Code (~/.claude.json)',
        },
        {
            path: getClaudeDesktopPath(),
            label: 'Claude Desktop',
        },
        {
            path: path.join(os.homedir(), '.cursor', 'mcp.json'),
            label: 'Cursor (~/.cursor/mcp.json)',
        },
        {
            path: path.join(os.homedir(), '.codeium', 'windsurf', 'mcp_config.json'),
            label: 'Windsurf (~/.codeium/windsurf/mcp_config.json)',
        },
    ];
    // Project .mcp.json files from repo paths
    const resolvedRepoPaths = repoPaths ?? getOlamRepoPaths();
    for (const repoPath of resolvedRepoPaths) {
        sourceDefs.push({
            path: path.join(repoPath, '.mcp.json'),
            label: `.mcp.json (${path.basename(repoPath)})`,
        });
    }
    // Parallel reads
    const reads = await Promise.all(sourceDefs.map(async ({ path: filePath, label }) => ({
        filePath,
        label,
        data: await Promise.resolve(readJsonFile(filePath)),
    })));
    const seen = new Set();
    for (const { filePath, label, data } of reads) {
        if (!data)
            continue;
        sources.push(label);
        const entries = extractMcpServers(data, filePath, label);
        for (const entry of entries) {
            // Deduplicate by name — first occurrence wins
            if (!seen.has(entry.name)) {
                seen.add(entry.name);
                allEntries.push(entry);
            }
        }
    }
    return {
        entries: allEntries,
        sources,
        durationMs: performance.now() - start,
    };
}
//# sourceMappingURL=import-discovery.js.map