import { CatalogMcpServerSchema } from '../lib/validation/contracts.js';
export function normalizeMcps(records, sourceId, today) {
    return records
        .map((entry) => CatalogMcpServerSchema.parse({
        ...ensureObject(entry),
        source: ensureObject(entry).source ?? sourceId,
        lastSeenAt: ensureObject(entry).lastSeenAt ?? today
    }))
        .sort((a, b) => a.id.localeCompare(b.id));
}
function ensureObject(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        throw new Error('Invalid MCP registry entry: expected object');
    }
    return value;
}
export function mergeMcpsById(mcps) {
    const state = new Map();
    for (const mcp of mcps) {
        const existing = state.get(mcp.id);
        if (!existing) {
            state.set(mcp.id, mcp);
            continue;
        }
        state.set(mcp.id, {
            ...existing,
            capabilities: dedupe([...existing.capabilities, ...mcp.capabilities]),
            compatibility: dedupe([...existing.compatibility, ...mcp.compatibility]),
            maintenanceSignal: Math.max(existing.maintenanceSignal, mcp.maintenanceSignal),
            adoptionSignal: Math.max(existing.adoptionSignal, mcp.adoptionSignal),
            lastSeenAt: mcp.lastSeenAt >= existing.lastSeenAt ? mcp.lastSeenAt : existing.lastSeenAt
        });
    }
    return Array.from(state.values()).sort((a, b) => a.id.localeCompare(b.id));
}
function dedupe(values) {
    return Array.from(new Set(values)).sort((a, b) => a.localeCompare(b));
}
