import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
export function loadMcpCatalog(mcpsDir) {
    const catalogPath = path.join(mcpsDir, '_catalog.yaml');
    if (!fs.existsSync(catalogPath)) {
        return { version: '0.0.0', categories: [] };
    }
    try {
        const raw = fs.readFileSync(catalogPath, 'utf-8');
        const parsed = yaml.load(raw);
        const catalog = parsed?.catalog;
        return {
            version: catalog?.version ?? '0.0.0',
            categories: catalog?.categories ?? [],
        };
    }
    catch {
        return { version: '0.0.0', categories: [] };
    }
}
export function listAllMcpIds(mcpsDir) {
    const catalog = loadMcpCatalog(mcpsDir);
    return catalog.categories.flatMap(c => c.mcps);
}
export function loadMcpDefinition(mcpsDir, id) {
    const defPath = path.join(mcpsDir, `${id}.mcp.yaml`);
    if (!fs.existsSync(defPath)) {
        return null;
    }
    try {
        const raw = fs.readFileSync(defPath, 'utf-8');
        const parsed = yaml.load(raw);
        if (!parsed?.id || !parsed?.detection) {
            return null;
        }
        return {
            id: parsed.id,
            name: parsed.name ?? parsed.id,
            description: parsed.description ?? '',
            category: parsed.category ?? 'other',
            icon: parsed.icon,
            detection: parsed.detection,
            server: parsed.server ?? { command: null, args: [], env: {} },
            auth: parsed.auth ?? [],
            tools: parsed.tools ?? [],
            relevant_sectors: parsed.relevant_sectors ?? [],
        };
    }
    catch {
        return null;
    }
}
