import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { configDir } from './config.js';
function sessionsDir() {
    return path.join(configDir(), 'sessions');
}
function sessionFile(cwd) {
    const hash = crypto.createHash('sha1').update(cwd).digest('hex').slice(0, 16);
    return path.join(sessionsDir(), `${hash}.json`);
}
/** Persist the session for this cwd (one saved session per directory). */
export function saveSession(cwd, model, messages) {
    try {
        fs.mkdirSync(sessionsDir(), { recursive: true });
        const session = {
            cwd,
            model,
            updatedAt: new Date().toISOString(),
            messages,
        };
        fs.writeFileSync(sessionFile(cwd), JSON.stringify(session));
    }
    catch {
        // Persistence is best-effort; never break a turn over it.
    }
}
export function loadSession(cwd) {
    try {
        const session = JSON.parse(fs.readFileSync(sessionFile(cwd), 'utf8'));
        if (!Array.isArray(session.messages) || session.messages.length === 0)
            return null;
        return session;
    }
    catch {
        return null;
    }
}
