"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeSnapshot = writeSnapshot;
exports.loadSnapshot = loadSnapshot;
const crypto_1 = require("crypto");
const fs_1 = require("fs");
const path_1 = require("path");
const atomic_js_1 = require("./atomic.js");
function writeSnapshot(runDir, snapshot) {
    try {
        // Compute checksum of snapshot content (without checksum field)
        const body = JSON.stringify(snapshot);
        const checksum = (0, crypto_1.createHash)('sha256').update(body).digest('hex');
        const withChecksum = JSON.stringify({ ...snapshot, _checksum: checksum });
        (0, atomic_js_1.atomicWriteSync)((0, path_1.join)(runDir, 'snapshot.json'), withChecksum);
    }
    catch {
        console.error('[snapshot] Warning: failed to write snapshot');
    }
}
function loadSnapshot(runDir) {
    const snapPath = (0, path_1.join)(runDir, 'snapshot.json');
    if (!(0, fs_1.existsSync)(snapPath))
        return null;
    const snapContent = (0, atomic_js_1.safeReadSync)(snapPath);
    if (snapContent instanceof Error)
        return null;
    try {
        const parsed = JSON.parse(snapContent);
        // New format: embedded _checksum
        if (parsed._checksum) {
            const { _checksum, ...rest } = parsed;
            const expectedBody = JSON.stringify(rest);
            const actualChecksum = (0, crypto_1.createHash)('sha256').update(expectedBody).digest('hex');
            if (actualChecksum !== _checksum) {
                console.error('[snapshot] Warning: checksum mismatch — will rebuild from WAL');
                return null;
            }
            return rest;
        }
        // Legacy format: external checksum file
        const checksumPath = (0, path_1.join)(runDir, 'snapshot.checksum');
        if (!(0, fs_1.existsSync)(checksumPath))
            return null;
        const expectedChecksum = (0, atomic_js_1.safeReadSync)(checksumPath);
        if (expectedChecksum instanceof Error)
            return null;
        const actualChecksum = (0, crypto_1.createHash)('sha256').update(snapContent).digest('hex');
        if (actualChecksum !== expectedChecksum.toString().trim()) {
            console.error('[snapshot] Warning: checksum mismatch — will rebuild from WAL');
            return null;
        }
        return parsed;
    }
    catch {
        return null;
    }
}
//# sourceMappingURL=snapshot.js.map