import { factSourceIds } from './helpers.js';
export function buildSourceLinkIndex(edges, nodes = []) {
    const links = new Map();
    const factTargets = new Map();
    for (const edge of edges) {
        if (edge.fromKind === 'source' && edge.toKind === 'node') {
            addSourceLink(links, edge.fromId, edge.toId);
        }
        else if (edge.fromKind === 'node' && edge.toKind === 'source') {
            addSourceLink(links, edge.toId, edge.fromId);
        }
        else if (edge.fromKind === 'node' && edge.toKind === 'node' && edge.relation === 'describes') {
            const current = factTargets.get(edge.fromId) ?? new Set();
            current.add(edge.toId);
            factTargets.set(edge.fromId, current);
        }
    }
    for (const edge of edges) {
        if (edge.fromKind !== 'source' || edge.toKind !== 'node' || edge.relation !== 'supports_fact')
            continue;
        for (const targetId of factTargets.get(edge.toId) ?? []) {
            addSourceLink(links, edge.fromId, targetId);
        }
    }
    for (const fact of nodes) {
        for (const targetId of factTargets.get(fact.id) ?? []) {
            for (const sourceId of factSourceIds(fact))
                addSourceLink(links, sourceId, targetId);
        }
    }
    return links;
}
function addSourceLink(links, sourceId, nodeId) {
    const current = links.get(sourceId) ?? new Set();
    current.add(nodeId);
    links.set(sourceId, current);
}
