"use strict";
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.InterruptionRecovery = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class InterruptionRecovery {
    recoveryPath;
    gapThresholdMs;
    constructor(cellDir) {
        this.recoveryPath = path.join(cellDir, 'recovery');
        this.gapThresholdMs = 10 * 60 * 1000;
        this.ensureDirectory(this.recoveryPath);
    }
    captureState(file, line, task, thought, projectId) {
        const state = {
            timestamp: new Date().toISOString(),
            file,
            line,
            task,
            thought,
            projectId,
        };
        fs.writeFileSync(path.join(this.recoveryPath, 'last-state.json'), JSON.stringify(state, null, 2), 'utf-8');
        return state;
    }
    detectInterruption() {
        const statePath = path.join(this.recoveryPath, 'last-state.json');
        if (!fs.existsSync(statePath))
            return null;
        try {
            const state = JSON.parse(fs.readFileSync(statePath, 'utf-8'));
            const elapsed = Date.now() - new Date(state.timestamp).getTime();
            if (elapsed > this.gapThresholdMs) {
                return state;
            }
            return null;
        }
        catch {
            return null;
        }
    }
    getContinuePrompt(state) {
        return `Continue working on "${state.task}"? You were at ${state.file}:${state.line}. Last thought: "${state.thought}"`;
    }
    getSummaryPrompt(state) {
        const elapsed = this.getElapsed(state.timestamp);
        return `You were away for ${elapsed}. Here's a summary: working on "${state.task}" in ${state.file}. Last thought: "${state.thought}"`;
    }
    getRestartPrompt() {
        return 'Start fresh. Previous context will be archived.';
    }
    getInterruptionStats() {
        const historyPath = path.join(this.recoveryPath, 'history.json');
        if (!fs.existsSync(historyPath))
            return { count: 0, averageGapMinutes: 0 };
        try {
            const history = JSON.parse(fs.readFileSync(historyPath, 'utf-8'));
            if (history.length === 0)
                return { count: 0, averageGapMinutes: 0 };
            const gaps = history.slice(1).map((h, i) => {
                return (new Date(h.timestamp).getTime() - new Date(history[i].timestamp).getTime()) / 60000;
            }).filter((g) => g > 0);
            const avg = gaps.length > 0 ? Math.round(gaps.reduce((a, b) => a + b, 0) / gaps.length) : 0;
            return { count: history.length, averageGapMinutes: avg };
        }
        catch {
            return { count: 0, averageGapMinutes: 0 };
        }
    }
    archive() {
        const statePath = path.join(this.recoveryPath, 'last-state.json');
        const historyPath = path.join(this.recoveryPath, 'history.json');
        if (fs.existsSync(statePath)) {
            try {
                const state = JSON.parse(fs.readFileSync(statePath, 'utf-8'));
                const history = fs.existsSync(historyPath)
                    ? JSON.parse(fs.readFileSync(historyPath, 'utf-8'))
                    : [];
                history.push(state);
                if (history.length > 50)
                    history.splice(0, history.length - 50);
                fs.writeFileSync(historyPath, JSON.stringify(history, null, 2), 'utf-8');
                fs.unlinkSync(statePath);
            }
            catch { }
        }
    }
    getElapsed(timestamp) {
        const diff = Date.now() - new Date(timestamp).getTime();
        const minutes = Math.floor(diff / 60000);
        if (minutes < 60)
            return `${minutes}m`;
        return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
    }
    ensureDirectory(dir) {
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
    }
}
exports.InterruptionRecovery = InterruptionRecovery;
//# sourceMappingURL=interruption-recovery.js.map