import { nexusEventBus } from './event-bus.js';
export class MemoryBackgroundWorker {
    memory;
    optimizationIntervalMs;
    timer;
    healthTick;
    constructor(memory, options = {}) {
        this.memory = memory;
        this.optimizationIntervalMs = options.optimizationIntervalMs ?? 300_000; // default 5 minutes
    }
    start() {
        if (this.timer)
            return;
        this.timer = setInterval(() => {
            this.optimize();
        }, this.optimizationIntervalMs);
        // Unref allows the process to exit if this is the only active timer
        if (this.timer.unref) {
            this.timer.unref();
        }
        this.startHealthTick();
    }
    stop() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = undefined;
        }
        if (this.healthTick) {
            clearInterval(this.healthTick);
            this.healthTick = undefined;
        }
    }
    optimize() {
        try {
            this.memory.maintenanceCycle();
        }
        catch (err) {
            console.error('[MemoryBackgroundWorker] Error during maintenance cycle:', err);
        }
    }
    startHealthTick() {
        if (this.healthTick)
            return;
        this.healthTick = setInterval(() => {
            try {
                const counts = this.memory.db.prepare(`
          SELECT state, COUNT(*) as c
          FROM memories
          GROUP BY state
        `).all();
                nexusEventBus.emit('memory.health.tick', {
                    counts,
                    ts: Date.now(),
                });
            }
            catch (err) {
                console.error('[MemoryBackgroundWorker] Error during health tick:', err);
            }
        }, 300_000);
        this.healthTick.unref();
    }
}
