"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.queuePersistence = exports.QueuePersistence = void 0;
const path_1 = require("path");
const config_js_1 = require("../../utils/config.js");
const logger_js_1 = require("../../utils/logger.js");
const file_ops_js_1 = require("../data-store/file-ops.js");
const log = (0, logger_js_1.createModuleLogger)('queue-persistence');
class QueuePersistence {
    pendingPath;
    failedPath;
    constructor(dataDir) {
        const dir = dataDir || config_js_1.config.dataDir;
        this.pendingPath = (0, path_1.resolve)(dir, 'queue', 'pending.json');
        this.failedPath = (0, path_1.resolve)(dir, 'queue', 'failed.json');
    }
    async init() {
        await (0, file_ops_js_1.ensureDir)((0, path_1.resolve)(this.pendingPath, '..'));
    }
    async savePending(items) {
        const pending = items.filter(i => i.status === 'pending' || i.status === 'processing');
        const failed = items.filter(i => i.status === 'failed');
        await (0, file_ops_js_1.atomicWriteJSON)(this.pendingPath, pending);
        await (0, file_ops_js_1.atomicWriteJSON)(this.failedPath, failed);
        log.debug({ pending: pending.length, failed: failed.length }, 'Queue state persisted');
    }
    async loadPending() {
        const pending = await (0, file_ops_js_1.readJSON)(this.pendingPath) || [];
        // Reset processing items back to pending (they were interrupted)
        for (const item of pending) {
            if (item.status === 'processing') {
                item.status = 'pending';
            }
        }
        log.info({ count: pending.length }, 'Loaded pending queue items');
        return pending;
    }
    async loadFailed() {
        return await (0, file_ops_js_1.readJSON)(this.failedPath) || [];
    }
    async loadAll() {
        const pending = await this.loadPending();
        const failed = await this.loadFailed();
        return [...pending, ...failed];
    }
}
exports.QueuePersistence = QueuePersistence;
exports.queuePersistence = new QueuePersistence();
//# sourceMappingURL=persistence.js.map