/**
 * Bidirectional BFS from a start node to find all connected nodes and edges.
 * Works with any graph structure (BPMN, flowchart, etc.).
 */
export function bfsPath(
  startId: string,
  edges: Array<{ from: string; to: string }>,
): { nodeSet: Set<string>; edgeSet: Set<string> } {
  const forward: Record<string, Array<{ from: string; to: string }>> = {};
  const backward: Record<string, Array<{ from: string; to: string }>> = {};

  for (const e of edges) {
    (forward[e.from] ??= []).push(e);
    (backward[e.to] ??= []).push(e);
  }

  const nodeSet = new Set([startId]);
  const edgeSet = new Set<string>();

  // Forward BFS
  let queue = [startId];
  while (queue.length) {
    const next: string[] = [];
    for (const nid of queue) {
      for (const e of forward[nid] ?? []) {
        const key = `${e.from}->${e.to}`;
        if (!edgeSet.has(key)) {
          edgeSet.add(key);
          nodeSet.add(e.to);
          next.push(e.to);
        }
      }
    }
    queue = next;
  }

  // Backward BFS
  queue = [startId];
  const visited = new Set([startId]);
  while (queue.length) {
    const next: string[] = [];
    for (const nid of queue) {
      for (const e of backward[nid] ?? []) {
        if (!visited.has(e.from)) {
          visited.add(e.from);
          edgeSet.add(`${e.from}->${e.to}`);
          nodeSet.add(e.from);
          next.push(e.from);
        }
      }
    }
    queue = next;
  }

  return { nodeSet, edgeSet };
}
