import {
  graphEdgeKey
} from "./chunk-Y4Z4I6WK.js";

// src/graph-dashboard-parser.ts
import path from "path";
import { readFile } from "fs/promises";
var GRAPH_TYPES = ["entity", "time", "causal"];
function graphFile(memoryDir, type) {
  return path.join(memoryDir, "state", "graphs", `${type}.jsonl`);
}
function isGraphEdge(raw, expectedType) {
  if (!raw || typeof raw !== "object") return false;
  const edge = raw;
  return edge.type === expectedType && typeof edge.from === "string" && edge.from.length > 0 && typeof edge.to === "string" && edge.to.length > 0 && typeof edge.weight === "number" && Number.isFinite(edge.weight) && typeof edge.label === "string" && typeof edge.ts === "string";
}
async function graphSnapshotFromMemoryDir(memoryDir) {
  const nodes = /* @__PURE__ */ new Set();
  const edges = [];
  const filesMissing = [];
  let malformedLines = 0;
  const seenEdges = /* @__PURE__ */ new Set();
  for (const type of GRAPH_TYPES) {
    const filePath = graphFile(memoryDir, type);
    let raw = "";
    try {
      raw = await readFile(filePath, "utf-8");
    } catch {
      filesMissing.push(type);
      continue;
    }
    for (const line of raw.split("\n")) {
      const trimmed = line.trim();
      if (!trimmed) continue;
      let parsed;
      try {
        parsed = JSON.parse(trimmed);
      } catch {
        malformedLines += 1;
        continue;
      }
      if (!isGraphEdge(parsed, type)) {
        malformedLines += 1;
        continue;
      }
      const key = graphEdgeKey(parsed);
      if (seenEdges.has(key)) continue;
      seenEdges.add(key);
      edges.push(parsed);
      nodes.add(parsed.from);
      nodes.add(parsed.to);
    }
  }
  const sortedEdges = edges.sort(
    (a, b) => a.type.localeCompare(b.type) || a.from.localeCompare(b.from) || a.to.localeCompare(b.to) || a.ts.localeCompare(b.ts)
  );
  const sortedNodes = [...nodes].sort((a, b) => a.localeCompare(b)).map((id) => ({ id }));
  return {
    generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
    nodes: sortedNodes,
    edges: sortedEdges,
    stats: {
      nodes: sortedNodes.length,
      edges: sortedEdges.length,
      malformedLines,
      filesMissing
    }
  };
}

export {
  graphSnapshotFromMemoryDir
};
//# sourceMappingURL=chunk-LIRZNNUP.js.map