// src/mcp/utils/graph-loader.ts
import * as path from "path";
import { stat } from "fs/promises";
var MAX_CACHE_ENTRIES = 8;
var cache = /* @__PURE__ */ new Map();
var pending = /* @__PURE__ */ new Map();
function clearGraphStoreCache() {
  cache.clear();
  pending.clear();
}
function evictIfNeeded() {
  if (cache.size > MAX_CACHE_ENTRIES) {
    const oldest = cache.keys().next().value;
    if (oldest !== void 0) cache.delete(oldest);
  }
}
async function doLoadGraphStore(projectRoot) {
  const { GraphStore } = await import("./dist-BZS2XRLG.js");
  const graphDir = path.join(projectRoot, ".harness", "graph");
  const store = new GraphStore();
  const loaded = await store.load(graphDir);
  if (!loaded) return null;
  return store;
}
async function loadGraphStore(projectRoot) {
  const graphDir = path.join(projectRoot, ".harness", "graph");
  const graphPath = path.join(graphDir, "graph.json");
  let mtimeMs;
  try {
    const stats = await stat(graphPath);
    mtimeMs = stats.mtimeMs;
  } catch {
    return null;
  }
  const cached = cache.get(projectRoot);
  if (cached && cached.mtimeMs === mtimeMs) {
    return cached.store;
  }
  const pendingLoad = pending.get(projectRoot);
  let promise;
  if (pendingLoad && pendingLoad.mtimeMs === mtimeMs) {
    promise = pendingLoad.promise;
  } else {
    promise = doLoadGraphStore(projectRoot);
    pending.set(projectRoot, { promise, mtimeMs });
  }
  const store = await promise;
  const currentPending = pending.get(projectRoot);
  if (currentPending && currentPending.promise === promise) {
    pending.delete(projectRoot);
  }
  if (store !== null) {
    cache.set(projectRoot, { store, mtimeMs });
    evictIfNeeded();
  }
  return store;
}

export {
  clearGraphStoreCache,
  loadGraphStore
};
