import { appendFileSync, existsSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { serializeFileEntries } from '../../core/session-schema.js';
import { findMostRecentSession, loadEntriesFromFile } from './session-schema-node-io.js';
export class FileSessionPersistenceBackend {
    ensureSessionDir(sessionDir) {
        if (sessionDir && !existsSync(sessionDir)) {
            mkdirSync(sessionDir, { recursive: true });
        }
    }
    normalizeSessionRef(sessionRef) {
        return resolve(sessionRef);
    }
    createSessionRef(sessionDir, sessionId, timestamp) {
        this.ensureSessionDir(sessionDir);
        const fileTimestamp = timestamp.replace(/[:.]/g, '-');
        return join(sessionDir, `${fileTimestamp}_${sessionId}.jsonl`);
    }
    sessionRefExists(sessionRef) {
        return existsSync(sessionRef);
    }
    loadEntries(sessionRef) {
        return loadEntriesFromFile(sessionRef);
    }
    rewriteEntries(sessionRef, entries) {
        this.ensureParentDir(sessionRef);
        writeFileSync(sessionRef, serializeFileEntries(entries));
    }
    appendEntries(sessionRef, entries) {
        if (entries.length === 0)
            return;
        this.ensureParentDir(sessionRef);
        appendFileSync(sessionRef, serializeFileEntries(entries));
    }
    findMostRecentSessionRef(sessionDir) {
        return findMostRecentSession(sessionDir);
    }
    deleteSessionRef(sessionRef) {
        if (existsSync(sessionRef)) {
            unlinkSync(sessionRef);
        }
    }
    ensureParentDir(sessionRef) {
        const parentDir = dirname(sessionRef);
        if (parentDir && !existsSync(parentDir)) {
            mkdirSync(parentDir, { recursive: true });
        }
    }
}
//# sourceMappingURL=session-persistence-backend.js.map