/**
 * Tool Event Bus - EDA for Tool Registry
 * @module core/tools/tool-event-bus
 * @since v0.35.0
 */
import { EventEmitter } from 'events';
import { consoleLogger } from '../../utils/logger.js';
const MAX_LISTENERS = 50;
export class ToolEventBus {
    constructor(options = {}) {
        this.emitter = new EventEmitter();
        this.emitter.setMaxListeners(MAX_LISTENERS);
        this.logger = options.logger ?? consoleLogger;
        this.handlerMap = new WeakMap();
    }
    on(eventType, handler) {
        const wrappedHandler = async (event) => {
            try {
                await handler(event);
            }
            catch (error) {
                this.logger.error(`Tool event handler error for ${eventType}: ${error}`);
            }
        };
        this.handlerMap.set(handler, wrappedHandler);
        this.emitter.on(eventType, wrappedHandler);
    }
    once(eventType, handler) {
        const wrappedHandler = async (event) => {
            try {
                await handler(event);
            }
            catch (error) {
                this.logger.error(`Tool event handler error for ${eventType}: ${error}`);
            }
        };
        this.emitter.once(eventType, wrappedHandler);
    }
    off(eventType, handler) {
        const wrappedHandler = this.handlerMap.get(handler);
        if (wrappedHandler) {
            this.emitter.off(eventType, wrappedHandler);
            this.handlerMap.delete(handler);
        }
    }
    emit(event) {
        this.logger.debug(`Emitting tool event: ${event.type}`);
        this.emitter.emit(event.type, event);
    }
    async emitAndWait(event) {
        this.logger.debug(`Emitting tool event (waiting): ${event.type}`);
        const listeners = this.emitter.listeners(event.type);
        const results = await Promise.allSettled(listeners.map(listener => listener(event)));
        for (const result of results) {
            if (result.status === 'rejected') {
                this.logger.error(`Tool event handler failed: ${result.reason}`);
            }
        }
    }
    removeAllListeners(eventType) {
        if (eventType) {
            this.emitter.removeAllListeners(eventType);
        }
        else {
            this.emitter.removeAllListeners();
        }
    }
    listenerCount(eventType) {
        return this.emitter.listenerCount(eventType);
    }
    onToolIndexed(handler) {
        this.on('ToolIndexed', handler);
    }
    onToolLoaded(handler) {
        this.on('ToolLoaded', handler);
    }
    onToolSelected(handler) {
        this.on('ToolSelected', handler);
    }
    onRegistryRebuilt(handler) {
        this.on('RegistryRebuilt', handler);
    }
}
//# sourceMappingURL=tool-event-bus.js.map