// engine/plugins/extensions/worker-extension.ts — Worker registration (SPEC-085 AC-05)
import { withPluginTimeout } from '../sandbox.js';
/** Registry of plugin workers keyed by `{pluginId}:{workerName}` */
const workerRegistry = new Map();
function workerKey(pluginId, workerName) {
    return `${pluginId}:${workerName}`;
}
/**
 * Registers workers from a plugin.
 * Cron workers start their interval immediately.
 * Event and manual workers are registered for invocation.
 */
export function registerPluginWorkers(pluginId, workers) {
    const registered = [];
    for (const worker of workers) {
        const key = workerKey(pluginId, worker.name);
        if (workerRegistry.has(key)) {
            throw new Error(`Worker "${worker.name}" already registered for plugin "${pluginId}"`);
        }
        const activeWorker = { pluginId, definition: worker };
        // Start cron workers immediately
        if (worker.trigger === 'cron' && worker.interval && worker.interval > 0) {
            activeWorker.intervalHandle = setInterval(() => {
                void withPluginTimeout(pluginId, `worker:${worker.name}`, worker.handler).catch(
                /* v8 ignore next 4 -- async cron error handler, not reachable in sync tests */
                (err) => {
                    const msg = err instanceof Error ? err.message : String(err);
                    console.error(`[plugin:${pluginId}] Worker "${worker.name}" error: ${msg}`);
                });
            }, worker.interval);
        }
        workerRegistry.set(key, activeWorker);
        registered.push(key);
    }
    return registered;
}
/**
 * Unregisters all workers belonging to a plugin and cancels any active intervals.
 */
export function unregisterPluginWorkers(pluginId) {
    const removed = [];
    for (const [key, worker] of workerRegistry) {
        if (worker.pluginId === pluginId) {
            if (worker.intervalHandle) {
                clearInterval(worker.intervalHandle);
            }
            workerRegistry.delete(key);
            removed.push(key);
        }
    }
    return removed;
}
/**
 * Invokes a manual worker by plugin ID and worker name.
 */
export async function invokeManualWorker(pluginId, workerName) {
    const key = workerKey(pluginId, workerName);
    const worker = workerRegistry.get(key);
    if (!worker) {
        throw new Error(`Worker "${workerName}" not found for plugin "${pluginId}"`);
    }
    if (worker.definition.trigger !== 'manual') {
        throw new Error(`Worker "${workerName}" is not a manual worker (trigger: ${worker.definition.trigger})`);
    }
    await withPluginTimeout(pluginId, `worker:${workerName}`, worker.definition.handler);
}
/**
 * Returns the count of workers registered for a specific plugin.
 */
export function getPluginWorkerCount(pluginId) {
    let count = 0;
    for (const worker of workerRegistry.values()) {
        if (worker.pluginId === pluginId) {
            count++;
        }
    }
    return count;
}
/**
 * Clears all workers and cancels intervals (for testing).
 */
export function clearWorkerRegistry() {
    for (const worker of workerRegistry.values()) {
        if (worker.intervalHandle) {
            clearInterval(worker.intervalHandle);
        }
    }
    workerRegistry.clear();
}
//# sourceMappingURL=worker-extension.js.map