// storage/audit-trail-store.ts — Append-only JSONL store for SPEC-387 EU AI Act audit trail
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { safeJsonParse } from './base-store.js';
/** Path to the global audit trail JSONL file. */
const AUDIT_FILE = join(process.cwd(), 'data', 'global', 'audit-trail.jsonl');
/** Ensure the data/global directory exists (called at module load). */
function ensureDataDir() {
    const dir = dirname(AUDIT_FILE);
    if (!existsSync(dir)) {
        mkdirSync(dir, { recursive: true });
    }
}
ensureDataDir();
/**
 * Append a single AuditTrailEntry to the JSONL file.
 * Synchronous to guarantee ordering relative to tool responses.
 * Never throws — errors are swallowed so audit failures never affect tool execution.
 */
export function appendEntry(entry) {
    try {
        writeFileSync(AUDIT_FILE, JSON.stringify(entry) + '\n', { flag: 'a', encoding: 'utf-8' });
    }
    catch {
        // Silent — audit must never affect tool execution
    }
}
/**
 * Read the hash of the last stored entry.
 * Returns empty string if the file does not exist or has no valid entries.
 * Used to build the prevHash for the next entry.
 */
export function getLastHash() {
    try {
        if (!existsSync(AUDIT_FILE)) {
            return '';
        }
        const content = readFileSync(AUDIT_FILE, 'utf-8');
        const lines = content.split('\n').filter((l) => l.trim().length > 0);
        if (lines.length === 0) {
            return '';
        }
        const lastLine = lines[lines.length - 1] ?? '';
        const parsed = safeJsonParse(lastLine, {});
        return typeof parsed.hash === 'string' ? parsed.hash : '';
    }
    catch {
        return '';
    }
}
/**
 * Read all entries from the JSONL file and apply optional filters.
 * Returns an empty array if the file does not exist or is unreadable.
 */
export function readEntries(filters) {
    try {
        if (!existsSync(AUDIT_FILE)) {
            return [];
        }
        const content = readFileSync(AUDIT_FILE, 'utf-8');
        const lines = content.split('\n').filter((l) => l.trim().length > 0);
        let entries = [];
        for (const line of lines) {
            const entry = safeJsonParse(line, null);
            if (entry !== null) {
                entries.push(entry);
            }
        }
        if (filters === undefined) {
            return entries;
        }
        if (filters.fromDate !== undefined) {
            const from = filters.fromDate;
            entries = entries.filter((e) => e.timestamp >= from);
        }
        if (filters.toDate !== undefined) {
            const to = filters.toDate;
            entries = entries.filter((e) => e.timestamp <= to);
        }
        if (filters.specId !== undefined) {
            const sid = filters.specId;
            entries = entries.filter((e) => e.specId === sid);
        }
        if (filters.projectPath !== undefined) {
            const pp = filters.projectPath;
            entries = entries.filter((e) => e.projectPath === pp);
        }
        if (filters.limit !== undefined && filters.limit > 0) {
            entries = entries.slice(0, filters.limit);
        }
        return entries;
    }
    catch {
        return [];
    }
}
//# sourceMappingURL=audit-trail-store.js.map