// storage/project-drift-store.ts — SPEC-666: Read/write drift signals from .planu/drift-commits.ndjson
import { readFile, writeFile, unlink, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { analyzeCommitRecord } from '../engine/project-drift-detector.js';
const DRIFT_FILE = 'drift-commits.ndjson';
function driftFilePath(projectPath) {
    return join(projectPath, '.planu', DRIFT_FILE);
}
/**
 * Read all unprocessed DriftCommitRecords from .planu/drift-commits.ndjson.
 * Returns an empty array if the file doesn't exist.
 */
export async function readDriftCommits(projectPath) {
    try {
        const raw = await readFile(driftFilePath(projectPath), 'utf-8');
        const records = [];
        for (const line of raw.split('\n')) {
            const trimmed = line.trim();
            if (!trimmed) {
                continue;
            }
            try {
                const parsed = JSON.parse(trimmed);
                if (parsed !== null && typeof parsed === 'object') {
                    records.push(parsed);
                }
            }
            catch {
                /* skip malformed lines */
            }
        }
        return records;
    }
    catch {
        return [];
    }
}
/**
 * Collect all drift signals from pending commit records and clear the file.
 * Returns the aggregated unique signals.
 * SPEC-666 AC4 prerequisite.
 */
export async function drainDriftQueue(projectPath) {
    const records = await readDriftCommits(projectPath);
    if (records.length === 0) {
        return [];
    }
    const allSignals = [];
    const seenKeys = new Set();
    for (const record of records) {
        for (const signal of analyzeCommitRecord(record)) {
            const key = `${signal.type}:${signal.value}`;
            if (!seenKeys.has(key)) {
                seenKeys.add(key);
                allSignals.push(signal);
            }
        }
    }
    // Clear the processed file
    await clearDriftCommits(projectPath);
    return allSignals;
}
/**
 * Remove the drift-commits.ndjson file (called after processing).
 * Best-effort — never throws.
 */
export async function clearDriftCommits(projectPath) {
    try {
        await unlink(driftFilePath(projectPath));
    }
    catch {
        /* file doesn't exist — that's fine */
    }
}
/**
 * Append a commit record to .planu/drift-commits.ndjson.
 * Used by tests and the post-commit hook (via shell).
 */
export async function appendDriftCommit(projectPath, record) {
    const dir = join(projectPath, '.planu');
    await mkdir(dir, { recursive: true });
    const line = JSON.stringify(record) + '\n';
    await writeFile(driftFilePath(projectPath), line, { flag: 'a', encoding: 'utf-8' });
}
//# sourceMappingURL=project-drift-store.js.map