import { existsSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { ensureDir, getDataDir } from '../storage/json-store.js';
import { listTemplates } from './agent.js';
function getMcpsDir() {
    return join(getDataDir(), 'mcps');
}
function getMcpMetaPath() {
    return join(getMcpsDir(), '_meta.json');
}
function readMeta() {
    const path = getMcpMetaPath();
    if (!existsSync(path))
        return { favorites: [] };
    try {
        return JSON.parse(readFileSync(path, 'utf-8'));
    }
    catch {
        return { favorites: [] };
    }
}
function writeMeta(meta) {
    ensureDir(getMcpsDir());
    writeFileSync(getMcpMetaPath(), JSON.stringify(meta, null, 2), 'utf-8');
}
function sanitizeName(name) {
    return name.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || 'mcp-server';
}
export function listMcps() {
    const agents = listTemplates();
    const mcpsDir = getMcpsDir();
    const meta = readMeta();
    ensureDir(mcpsDir);
    const files = readdirSync(mcpsDir)
        .filter((f) => f.endsWith('.json') && !f.startsWith('_'));
    return files.map((filename) => {
        const raw = readFileSync(join(mcpsDir, filename), 'utf-8');
        const parsed = JSON.parse(raw);
        const name = parsed.name || filename.replace(/\.json$/, '');
        const boundAgents = agents
            .filter((a) => {
            const mcps = a.mcps;
            if (!mcps || typeof mcps !== 'object')
                return false;
            const servers = mcps.mcpServers;
            return servers && name in servers;
        })
            .map((a) => ({
            id: a.id,
            name: a.name || 'Agent',
            avatarUrl: a.avatarUrl,
        }));
        return {
            name,
            description: parsed.description || '',
            config: parsed.config || {},
            favorited: meta.favorites.includes(name),
            boundAgents,
        };
    });
}
export function importMcps(jsonText) {
    const parsed = JSON.parse(jsonText);
    const servers = {};
    // Support both { mcpServers: {...} } and flat { name: {...} } formats
    if (parsed.mcpServers && typeof parsed.mcpServers === 'object') {
        Object.assign(servers, parsed.mcpServers);
    }
    else if (typeof parsed === 'object') {
        Object.assign(servers, parsed);
    }
    const mcpsDir = getMcpsDir();
    ensureDir(mcpsDir);
    const results = [];
    for (const [rawName, config] of Object.entries(servers)) {
        const name = sanitizeName(rawName);
        const filePath = join(mcpsDir, `${name}.json`);
        writeFileSync(filePath, JSON.stringify({ name, config }, null, 2), 'utf-8');
        results.push({
            name,
            description: '',
            config: config,
            favorited: false,
            boundAgents: [],
        });
    }
    return results;
}
export function updateMcpConfig(name, config) {
    const mcpsDir = getMcpsDir();
    const filePath = join(mcpsDir, `${name}.json`);
    if (!existsSync(filePath))
        return false;
    const raw = readFileSync(filePath, 'utf-8');
    const parsed = JSON.parse(raw);
    parsed.config = config;
    writeFileSync(filePath, JSON.stringify(parsed, null, 2), 'utf-8');
    return true;
}
export function deleteMcp(name) {
    const mcpsDir = getMcpsDir();
    const filePath = join(mcpsDir, `${name}.json`);
    if (!existsSync(filePath))
        return false;
    unlinkSync(filePath);
    return true;
}
export function toggleFavorite(name) {
    const meta = readMeta();
    const idx = meta.favorites.indexOf(name);
    if (idx >= 0) {
        meta.favorites.splice(idx, 1);
    }
    else {
        meta.favorites.push(name);
    }
    writeMeta(meta);
    return idx < 0;
}
//# sourceMappingURL=mcp.js.map