"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.OfflineQueue = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const crypto_1 = require("crypto");
class OfflineQueue {
    queuePath;
    statusPath;
    maxRetries;
    timeoutMs;
    lastFlush;
    constructor(cellDir) {
        this.queuePath = path.join(cellDir, 'offline', 'queue.json');
        this.statusPath = path.join(cellDir, 'offline', 'status.json');
        this.maxRetries = 3;
        this.timeoutMs = 5000;
        this.lastFlush = null;
        this.ensureDirectory(path.dirname(this.queuePath));
    }
    enqueue(type, data) {
        const signal = {
            id: `q_${Date.now()}_${(0, crypto_1.randomUUID)().substring(0, 8)}`,
            type,
            data,
            timestamp: new Date().toISOString(),
            retryCount: 0,
        };
        const queue = this.loadQueue();
        queue.push(signal);
        this.saveQueue(queue);
        return signal;
    }
    dequeue() {
        const queue = this.loadQueue();
        if (queue.length === 0)
            return null;
        const signal = queue.shift();
        this.saveQueue(queue);
        return signal;
    }
    peek() {
        const queue = this.loadQueue();
        return queue.length > 0 ? queue[0] : null;
    }
    getQueueSize() {
        return this.loadQueue().length;
    }
    getPendingCount() {
        return this.loadQueue().length;
    }
    getLastFlush() {
        return this.lastFlush;
    }
    async syncOnReconnect(sendFn) {
        const queue = this.loadQueue();
        let synced = 0;
        let failed = 0;
        const remaining = [];
        for (const signal of queue) {
            if (signal.retryCount >= this.maxRetries) {
                failed++;
                continue;
            }
            let sent = false;
            if (sendFn) {
                try {
                    sent = await sendFn(signal);
                }
                catch {
                    sent = false;
                }
            }
            if (sent) {
                synced++;
            }
            else {
                signal.retryCount++;
                remaining.push(signal);
            }
        }
        this.lastFlush = new Date().toISOString();
        this.saveQueue(remaining);
        return { synced, failed };
    }
    checkEngineHealth() {
        const status = this.loadStatus();
        const now = Date.now();
        const lastHeartbeat = new Date(status.lastHeartbeat).getTime();
        if (now - lastHeartbeat > this.timeoutMs) {
            status.consecutiveFailures++;
            if (status.consecutiveFailures >= 3) {
                status.state = 'OFFLINE';
            }
            else {
                status.state = 'DEGRADED';
            }
        }
        else {
            status.state = 'ONLINE';
            status.consecutiveFailures = 0;
        }
        this.saveStatus(status);
        return status;
    }
    heartbeat() {
        const status = this.loadStatus();
        status.lastHeartbeat = new Date().toISOString();
        status.state = 'ONLINE';
        status.consecutiveFailures = 0;
        this.saveStatus(status);
    }
    getDegradedMessage(status) {
        switch (status.state) {
            case 'DEGRADED':
                return `Engine is degraded (${status.consecutiveFailures} failures). Retrying...`;
            case 'OFFLINE':
                return `Engine is OFFLINE. ${this.getQueueSize()} signals queued locally. Will sync on reconnect. Admin alert sent.`;
            default:
                return 'Engine is online.';
        }
    }
    clearQueue() {
        this.saveQueue([]);
    }
    loadQueue() {
        if (!fs.existsSync(this.queuePath))
            return [];
        try {
            return JSON.parse(fs.readFileSync(this.queuePath, 'utf-8'));
        }
        catch {
            return [];
        }
    }
    saveQueue(queue) {
        fs.writeFileSync(this.queuePath, JSON.stringify(queue, null, 2), 'utf-8');
    }
    loadStatus() {
        if (!fs.existsSync(this.statusPath)) {
            return { state: 'ONLINE', lastHeartbeat: new Date().toISOString(), consecutiveFailures: 0 };
        }
        try {
            return JSON.parse(fs.readFileSync(this.statusPath, 'utf-8'));
        }
        catch {
            return { state: 'ONLINE', lastHeartbeat: new Date().toISOString(), consecutiveFailures: 0 };
        }
    }
    saveStatus(status) {
        fs.writeFileSync(this.statusPath, JSON.stringify(status, null, 2), 'utf-8');
    }
    ensureDirectory(dir) {
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
    }
}
exports.OfflineQueue = OfflineQueue;
//# sourceMappingURL=offline-queue.js.map