const handlers = new Map();
let emitCount = 0;
function addHandler(eventType, handler) {
    const set = handlers.get(eventType) ?? new Set();
    if (!handlers.has(eventType)) {
        handlers.set(eventType, set);
    }
    set.add(handler);
    return () => {
        set.delete(handler);
        if (set.size === 0) {
            handlers.delete(eventType);
        }
    };
}
export function on(eventType, handler) {
    return addHandler(eventType, handler);
}
export function once(eventType, handler) {
    let fired = false;
    const wrapped = (payload) => {
        if (fired)
            return;
        fired = true;
        return handler(payload);
    };
    const unsubscribe = addHandler(eventType, wrapped);
    const combined = () => {
        fired = true;
        unsubscribe();
    };
    return combined;
}
export async function emit(event) {
    const set = handlers.get(event.type);
    if (!set || set.size === 0)
        return;
    emitCount++;
    for (const handler of set) {
        try {
            await handler(event.payload);
        }
        catch (err) {
            const message = err instanceof Error ? err.message : String(err);
            console.error(`[hook-bus] Handler error for ${event.type}: ${message}`);
        }
    }
}
export function getStats() {
    let registeredHandlers = 0;
    for (const set of handlers.values()) {
        registeredHandlers += set.size;
    }
    return { registeredHandlers, emittedEvents: emitCount };
}
export function clearHandlers() {
    handlers.clear();
    emitCount = 0;
}
