import { readFile } from "node:fs/promises";
import { atomicWriteFile } from "./_shared.js";
/**
 * Get the graph store path from an index path.
 * {hash}.index.json → {hash}.graph.json
 */
export function getGraphPath(indexPath) {
    return indexPath.replace(/\.index\.json$/, ".graph.json");
}
/** Simple FNV-1a hash for content-change detection. */
function fnv1a(text) {
    let h = 0x811c9dc5;
    for (let i = 0; i < text.length; i++) {
        h ^= text.charCodeAt(i);
        h = Math.imul(h, 0x01000193);
    }
    return (h >>> 0).toString(16);
}
/** Compute a hash from index file paths + symbol counts (cheap staleness check). */
export function computeIndexHash(files) {
    const fingerprint = files.map((f) => `${f.path}:${f.symbol_count}`).join("\n");
    return fnv1a(fingerprint);
}
/**
 * Load a persisted graph. Returns null if not found, corrupted, or stale.
 */
export async function loadGraph(graphPath, currentIndexHash) {
    try {
        const raw = await readFile(graphPath, "utf-8");
        const parsed = JSON.parse(raw);
        if (typeof parsed === "object" && parsed !== null &&
            typeof parsed["index_hash"] === "string" &&
            Array.isArray(parsed["edges"])) {
            const graph = parsed;
            // Stale check: index changed since last computation
            if (graph.index_hash !== currentIndexHash)
                return null;
            return graph;
        }
        return null;
    }
    catch {
        return null;
    }
}
/**
 * Save a computed graph to disk.
 */
export async function saveGraph(graphPath, graph) {
    await atomicWriteFile(graphPath, JSON.stringify(graph));
}
//# sourceMappingURL=graph-store.js.map