// engine/housekeeping/history-log.ts — SPEC-751
// Hash-chained JSONL backup log for deleted housekeeping items.
// Mirrors the SPEC-723/734 transition-log pattern for recoverability.
import { createHash, randomUUID } from 'node:crypto';
import { appendFile, readFile, mkdir } from 'node:fs/promises';
import { dirname, join } from 'node:path';
// ---------------------------------------------------------------------------
// Path helper
// ---------------------------------------------------------------------------
export function housekeepingHistoryPath(projectPath) {
    return join(projectPath, 'planu', '.housekeeping-history.jsonl');
}
// ---------------------------------------------------------------------------
// Hash chain helpers
// ---------------------------------------------------------------------------
function canonicalEntry(entry) {
    return JSON.stringify({
        id: entry.id,
        deletedAt: entry.deletedAt,
        projectPath: entry.projectPath,
        kind: entry.kind,
        ref: entry.ref,
        sha: entry.sha,
        prevSha: entry.prevSha,
    });
}
function computeSha256(entry) {
    return createHash('sha256').update(canonicalEntry(entry), 'utf8').digest('hex');
}
// ---------------------------------------------------------------------------
// Per-file write queue (serialize to maintain chain integrity)
// ---------------------------------------------------------------------------
const writeQueues = new Map();
async function readLastSha(filePath) {
    try {
        const content = await readFile(filePath, 'utf-8');
        const lines = content.trim().split('\n').filter(Boolean);
        if (lines.length === 0) {
            return '';
        }
        const lastLine = lines[lines.length - 1] ?? '';
        const parsed = JSON.parse(lastLine);
        return typeof parsed.sha256 === 'string' ? parsed.sha256 : '';
    }
    catch {
        return '';
    }
}
async function doAppend(filePath, input) {
    await mkdir(dirname(filePath), { recursive: true });
    const prevSha = await readLastSha(filePath);
    const partial = {
        id: randomUUID(),
        deletedAt: new Date().toISOString(),
        projectPath: input.projectPath,
        kind: input.kind,
        ref: input.ref,
        sha: input.sha,
        prevSha,
    };
    const sha256 = computeSha256(partial);
    const entry = { ...partial, sha256 };
    await appendFile(filePath, JSON.stringify(entry) + '\n', 'utf-8');
    return entry;
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
export function appendHousekeepingEntry(projectPath, input) {
    const filePath = housekeepingHistoryPath(projectPath);
    let result;
    const next = (writeQueues.get(filePath) ?? Promise.resolve()).then(async () => {
        result = await doAppend(filePath, input);
    });
    writeQueues.set(filePath, next.then(() => undefined, () => undefined));
    return next.then(() => result);
}
//# sourceMappingURL=history-log.js.map