import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
export class FileStateCache {
    snapshots = new Map();
    rememberRead(projectRoot, filePath) {
        const snapshot = snapshotFile(projectRoot, filePath);
        this.snapshots.set(normalizeKey(filePath), snapshot);
        return snapshot;
    }
    get(filePath) {
        return this.snapshots.get(normalizeKey(filePath));
    }
    checkFresh(projectRoot, filePath) {
        const prior = this.get(filePath);
        if (!prior) {
            return { fresh: false, reason: "file was not read in this session before write/patch" };
        }
        const current = snapshotFile(projectRoot, filePath);
        if (current.sha256 !== prior.sha256) {
            return { fresh: false, reason: "file changed after last read" };
        }
        return { fresh: true };
    }
    checkFreshForWrite(projectRoot, filePath) {
        const fullPath = path.resolve(projectRoot, filePath);
        if (!fs.existsSync(fullPath))
            return { fresh: true };
        return this.checkFresh(projectRoot, filePath);
    }
}
export function snapshotFile(projectRoot, filePath) {
    const fullPath = path.resolve(projectRoot, filePath);
    const stat = fs.statSync(fullPath);
    const content = fs.readFileSync(fullPath);
    return {
        path: filePath.replaceAll("\\", "/"),
        sha256: crypto.createHash("sha256").update(content).digest("hex"),
        size: stat.size,
        mtimeMs: stat.mtimeMs,
        readAtMs: Date.now(),
    };
}
function normalizeKey(filePath) {
    return filePath.replaceAll("\\", "/").toLowerCase();
}
