import { logger } from '../utils/logger.js';
export class SharedSessionRuntimeBusBridge {
    busAttached = false;
    busUnsubs = [];
    attach(bus, sessionResolver, completeAgent) {
        if (this.busAttached) {
            logger.warn('[SharedSessionBroker] attachRuntimeBus called more than once — ignoring duplicate call', {});
            return () => { };
        }
        this.busAttached = true;
        const onCompleted = bus.on('AGENT_COMPLETED', (envelope) => {
            if (typeof envelope.payload?.agentId !== 'string')
                return;
            const sessionId = sessionResolver(envelope.payload.agentId);
            if (!sessionId)
                return;
            completeAgent(sessionId, envelope.payload.agentId, envelope.payload.output ?? '', { status: 'completed', durationMs: envelope.payload.durationMs }).catch((error) => {
                logger.error('[SharedSessionBroker] completeAgent error on AGENT_COMPLETED', { error: String(error) });
            });
        });
        const onFailed = bus.on('AGENT_FAILED', (envelope) => {
            if (typeof envelope.payload?.agentId !== 'string')
                return;
            const sessionId = sessionResolver(envelope.payload.agentId);
            if (!sessionId)
                return;
            completeAgent(sessionId, envelope.payload.agentId, envelope.payload.error, { status: 'failed', durationMs: envelope.payload.durationMs }).catch((error) => {
                logger.error('[SharedSessionBroker] completeAgent error on AGENT_FAILED', { error: String(error) });
            });
        });
        const onCancelled = bus.on('AGENT_CANCELLED', (envelope) => {
            if (typeof envelope.payload?.agentId !== 'string')
                return;
            const sessionId = sessionResolver(envelope.payload.agentId);
            if (!sessionId)
                return;
            completeAgent(sessionId, envelope.payload.agentId, envelope.payload.reason ?? 'cancelled', { status: 'cancelled' }).catch((error) => {
                logger.error('[SharedSessionBroker] completeAgent error on AGENT_CANCELLED', { error: String(error) });
            });
        });
        this.busUnsubs.push(onCompleted, onFailed, onCancelled);
        return () => {
            onCompleted();
            onFailed();
            onCancelled();
            this.busAttached = false;
            this.busUnsubs = this.busUnsubs.filter((fn) => fn !== onCompleted && fn !== onFailed && fn !== onCancelled);
        };
    }
    stopAll() {
        for (const unsubscribe of this.busUnsubs) {
            try {
                unsubscribe();
            }
            catch (error) {
                logger.warn('SharedSessionBroker bus unsubscribe failed', {
                    error: error instanceof Error ? error.message : String(error),
                });
            }
        }
        this.busUnsubs = [];
        this.busAttached = false;
    }
}
