import path from 'node:path';
import crypto from 'node:crypto';
import { ensureDir, nowIso, readJson, writeJsonAtomic } from '../fsx.js';
export const GATE_CACHE_SCHEMA = 'sks.release-gate-cache.v1';
export function gateCacheKey(input) {
    const canonical = JSON.stringify({
        g: input.gateId,
        c: input.command,
        v: input.packageVersion,
        h: input.gitCommit,
        i: [...input.inputHashes].sort(),
        e: input.envMode,
        d: input.distHash,
        m: input.manifestHash || '',
        s: input.packageScriptsHash || '',
        gimpl: input.gateImplementationHash || '',
        node: input.nodeVersion || '',
        npm: input.npmVersion || ''
    });
    return crypto.createHash('sha256').update(canonical).digest('hex');
}
export function gateCachePath(root) {
    return path.join(path.resolve(root), '.sneakoscope', 'reports', 'gate-cache.json');
}
export async function readGateCache(root) {
    const file = await readJson(gateCachePath(root), null);
    if (file && file.schema === GATE_CACHE_SCHEMA && file.records)
        return file;
    return { schema: GATE_CACHE_SCHEMA, records: {} };
}
export async function writeGateCache(root, cache) {
    const file = gateCachePath(root);
    await ensureDir(path.dirname(file));
    await writeJsonAtomic(file, cache);
    return file;
}
export function recordGateResult(cache, key, gateId, ok, durationMs) {
    cache.records[key] = { key, gate_id: gateId, ok, duration_ms: durationMs, recorded_at: nowIso() };
    return cache;
}
export function lookupGateResult(cache, key) {
    return cache.records[key] ?? null;
}
//# sourceMappingURL=gate-cache.js.map