"use strict";
// Session Recovery — Crash-proof snapshots + restore
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.initRecovery = initRecovery;
exports.trackActivity = trackActivity;
exports.incrementSignals = incrementSignals;
exports.incrementPatterns = incrementPatterns;
exports.takeSnapshot = takeSnapshot;
exports.getLatestSnapshot = getLatestSnapshot;
exports.getRecoveryMessage = getRecoveryMessage;
exports.stopRecovery = stopRecovery;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const SNAPSHOT_DIR = path.join(os.homedir(), '.fivo', 'cell', 'snapshots');
const MAX_SNAPSHOTS = 10;
const SNAPSHOT_INTERVAL_MS = 30000;
const MAX_SNAPSHOT_AGE_MS = 7 * 24 * 60 * 60 * 1000;
class SessionRecovery {
    sessionStart = Date.now();
    signalCount = 0;
    patternCount = 0;
    currentProject = '';
    lastFile = '';
    lastLine = 0;
    intervalId = null;
    previousSigterm = [];
    previousSigint = [];
    init(projectPath) {
        if (!fs.existsSync(SNAPSHOT_DIR))
            fs.mkdirSync(SNAPSHOT_DIR, { recursive: true });
        this.currentProject = projectPath;
        this.sessionStart = Date.now();
        this.intervalId = setInterval(() => this.snapshot(), SNAPSHOT_INTERVAL_MS);
        this.previousSigterm = process.listeners('SIGTERM');
        this.previousSigint = process.listeners('SIGINT');
        process.removeAllListeners('SIGTERM');
        process.removeAllListeners('SIGINT');
        process.once('SIGTERM', () => { this.snapshot(); for (const cb of this.previousSigterm)
            cb(); process.exit(0); });
        process.once('SIGINT', () => { this.snapshot(); for (const cb of this.previousSigint)
            cb(); process.exit(0); });
    }
    trackActivity(file, line) { this.lastFile = file; this.lastLine = line; }
    incrementSignals(count = 1) { this.signalCount += count; }
    incrementPatterns(count = 1) { this.patternCount += count; }
    snapshot() {
        const snap = {
            timestamp: new Date().toISOString(),
            projectPath: this.currentProject,
            signalCount: this.signalCount,
            patternCount: this.patternCount,
            sessionDuration: Math.round((Date.now() - this.sessionStart) / 1000),
            lastFile: this.lastFile || undefined,
            lastLine: this.lastLine || undefined,
        };
        try {
            const file = path.join(SNAPSHOT_DIR, `${Date.now()}.json`);
            fs.writeFileSync(file, JSON.stringify(snap));
            this.cleanupSnapshots();
        }
        catch { }
        return snap;
    }
    getLatestSnapshot() {
        if (!fs.existsSync(SNAPSHOT_DIR))
            return null;
        const files = fs.readdirSync(SNAPSHOT_DIR).filter(f => f.endsWith('.json')).sort().reverse();
        if (files.length === 0)
            return null;
        return JSON.parse(fs.readFileSync(path.join(SNAPSHOT_DIR, files[0]), 'utf-8'));
    }
    getRecoveryMessage() {
        const snap = this.getLatestSnapshot();
        if (!snap)
            return 'No previous session found. Starting fresh.';
        const age = Date.now() - new Date(snap.timestamp).getTime();
        if (age > MAX_SNAPSHOT_AGE_MS)
            return 'Previous session is too old. Starting fresh.';
        return `Cell detected an unclean shutdown.\nLast session: ${snap.projectPath}\n${snap.signalCount} signals, ${snap.patternCount} patterns\nDuration: ${Math.round(snap.sessionDuration / 60)}min\n[Continue where you left off] [Start fresh]`;
    }
    stop() {
        if (this.intervalId) {
            clearInterval(this.intervalId);
            this.intervalId = null;
        }
        this.snapshot();
    }
    cleanupSnapshots() {
        const files = fs.readdirSync(SNAPSHOT_DIR).filter(f => f.endsWith('.json')).sort();
        while (files.length > MAX_SNAPSHOTS) {
            fs.unlinkSync(path.join(SNAPSHOT_DIR, files.shift()));
        }
    }
}
const recovery = new SessionRecovery();
function initRecovery(projectPath) { recovery.init(projectPath); }
function trackActivity(file, line) { recovery.trackActivity(file, line); }
function incrementSignals(count = 1) { recovery.incrementSignals(count); }
function incrementPatterns(count = 1) { recovery.incrementPatterns(count); }
function takeSnapshot() { return recovery.snapshot(); }
function getLatestSnapshot() { return recovery.getLatestSnapshot(); }
function getRecoveryMessage() { return recovery.getRecoveryMessage(); }
function stopRecovery() { recovery.stop(); }
//# sourceMappingURL=session-recovery.js.map