import { Logger, NodeSingletons, workersConfig } from '../../../../src/index.js';
import { HealthMonitor } from '../HealthMonitor.js';
import { getWorkers } from '../dashboard/workers-api.js';
const createFallbackEmitter = () => {
    const listeners = new Map();
    return {
        on(event, listener) {
            const set = listeners.get(event) ?? new Set();
            set.add(listener);
            listeners.set(event, set);
        },
        off(event, listener) {
            const set = listeners.get(event);
            if (!set)
                return;
            set.delete(listener);
            if (set.size === 0)
                listeners.delete(event);
        },
        emit(event, payload) {
            const set = listeners.get(event);
            if (!set)
                return false;
            for (const listener of set)
                listener(payload);
            return true;
        },
    };
};
// Internal state
const EventEmitterCtor = NodeSingletons?.EventEmitter;
const emitter = typeof EventEmitterCtor === 'function' ? new EventEmitterCtor() : createFallbackEmitter();
emitter.setMaxListeners?.(Infinity);
let interval = null;
let subscribers = 0;
const INTERVAL_MS = workersConfig?.intervalMs || 5000;
const broadcastSnapshot = async () => {
    try {
        if (subscribers <= 0)
            return;
        const monitoring = await HealthMonitor.getSummary();
        // Fetch full workers listing optimized for dashboard
        const workersPayload = await getWorkers({ page: 1, limit: 200 });
        const payload = {
            type: 'snapshot',
            ts: new Date().toISOString(),
            monitoring,
            workers: workersPayload,
        };
        emitter.emit('snapshot', payload);
    }
    catch (err) {
        Logger.error('WorkerMonitoringService.broadcastSnapshot failed', err);
        emitter.emit('error', err);
    }
};
const startPolling = () => {
    if (interval)
        return;
    Logger.debug('Starting WorkerMonitoringService polling');
    // Initial fetch
    void broadcastSnapshot();
    interval = setInterval(() => {
        void broadcastSnapshot();
    }, INTERVAL_MS);
};
const stopPolling = () => {
    if (interval) {
        Logger.debug('Stopping WorkerMonitoringService polling');
        clearInterval(interval);
        interval = null;
    }
};
export const WorkerMonitoringService = Object.freeze({
    subscribe(callback) {
        emitter.on('snapshot', callback);
        subscribers++;
        if (subscribers === 1) {
            startPolling();
        }
    },
    unsubscribe(callback) {
        emitter.off('snapshot', callback);
        subscribers--;
        if (subscribers <= 0) {
            stopPolling();
        }
    },
});
