import { ItemLotTraceResponse } from "@/app/api/itemTracing";
import {
  buildTraceGraphLayout,
  TraceGraphLayout,
  TraceGraphLayoutNode,
} from "./traceGraphLayout";
import { resolveTraceFlowEdgePairs } from "./traceGraphSemantics";
import type { TraceGraphCompileLabels } from "./traceGraphLabels";

export type TraceFlowEdgePair = { fromId: string; toId: string };

export type CompiledTraceGraph = {
  layout: TraceGraphLayout;
  edgePairs: TraceFlowEdgePair[];
  nodes: TraceGraphLayoutNode[];
};

export const compileTraceGraph = (
  data: ItemLotTraceResponse,
  labels: TraceGraphCompileLabels,
): CompiledTraceGraph => {
  const layout = buildTraceGraphLayout(data, labels);
  const backendEdges = data.traceGraph?.edges?.map((e) => ({
    fromKey: e.fromKey,
    toKey: e.toKey,
  }));
  const edgePairs = resolveTraceFlowEdgePairs(layout.nodes, layout.phaseOrder, backendEdges);
  return {
    layout,
    edgePairs,
    nodes: layout.nodes,
  };
};
