export class CumulativeTradeFlowResolver {
    static resolve({ nodeIds = [], producedByNodeId = new Map(), centerByNodeId = new Map() } = {}) {
        const normalizedNodeIds = [...new Set((nodeIds || []).map(String).filter(Boolean))];
        const knownNodeIds = new Set(normalizedNodeIds);
        const childrenByCenterNodeId = new Map();
        for (const [rawNodeId, rawCenterNodeId] of centerByNodeId || []) {
            const nodeId = String(rawNodeId || "");
            const centerNodeId = String(rawCenterNodeId || "");
            if (!knownNodeIds.has(nodeId) || !knownNodeIds.has(centerNodeId) || nodeId === centerNodeId) continue;
            const children = childrenByCenterNodeId.get(centerNodeId) || [];
            children.push(nodeId);
            childrenByCenterNodeId.set(centerNodeId, children);
        }

        const exportsByNodeId = new Map();
        const visiting = new Set();
        const collect = nodeId => {
            if (exportsByNodeId.has(nodeId)) return exportsByNodeId.get(nodeId);
            if (!knownNodeIds.has(nodeId) || visiting.has(nodeId)) return [];
            visiting.add(nodeId);
            const goods = new Set(producedByNodeId.get(nodeId) || []);
            for (const childNodeId of childrenByCenterNodeId.get(nodeId) || []) {
                for (const goodId of collect(childNodeId)) goods.add(goodId);
            }
            visiting.delete(nodeId);
            const result = [...goods];
            exportsByNodeId.set(nodeId, result);
            return result;
        };
        for (const nodeId of normalizedNodeIds) collect(nodeId);
        return { exportsByNodeId, childrenByCenterNodeId };
    }
}
