import { getLogger } from "../../../../util/logger.js";
export class RetryNotificationObserver {
    peer;
    chatSessionStore;
    logger = getLogger();
    constructor(options = {}) {
        this.peer = options.peer;
        this.chatSessionStore = options.chatSessionStore;
        this.logger.info(`[retry-notification] Observer created, peer=${!!options.peer}, chatSessionStore=${!!options.chatSessionStore}`);
    }
    attach(events, _config) {
        this.logger.info("[retry-notification] Attaching to event bus");
        // Handle retry with same provider - notify on every retry
        events.on("retry", (_error, attempt, delayMs) => {
            this.logger.info(`[retry-notification] RETRY EVENT: attempt=${attempt}, delayMs=${delayMs}`);
            this.handleRetry(attempt, delayMs);
        });
        // Handle fallback to different provider
        events.on("fallback", (from, to, reason) => {
            this.logger.info(`[retry-notification] FALLBACK EVENT: from=${from.name}/${from.model} to=${to.name}/${to.model}, reason=${reason}`);
            this.handleFallback(from, to, reason);
        });
    }
    handleRetry(attempt, delayMs) {
        if (!this.peer) {
            this.logger.warn("[retry-notification] No peer, cannot send notification");
            return;
        }
        const delaySeconds = Math.round(delayMs / 1000);
        const message = {
            role: "system",
            type: "retry_notification",
            content: "",
            retryType: "same_provider",
            attempt,
            delaySeconds,
        };
        this.sendNotification(message);
    }
    handleFallback(from, to, reason) {
        if (!this.peer) {
            this.logger.warn("[retry-notification] No peer, cannot send fallback notification");
            return;
        }
        const message = {
            role: "system",
            type: "retry_notification",
            content: "",
            retryType: "fallback_provider",
            fromProvider: `${from.name}/${from.model}`,
            toProvider: `${to.name}/${to.model}`,
            reason,
        };
        this.sendNotification(message);
    }
    sendNotification(message) {
        this.logger.info(`[retry-notification] Sending ${message.retryType} notification to UI`);
        void this.peer.call.aiPushMessage(message)
            .then(() => {
            this.logger.info("[retry-notification] Message sent to UI successfully");
            if (this.chatSessionStore) {
                void this.chatSessionStore.recordAssistant(message);
            }
        })
            .catch((err) => {
            // Failed to send is expected when clients disconnect - log as WARNING
            this.logger.warn("[retry-notification] Failed to send message", err);
        });
    }
}
//# sourceMappingURL=retry-notification.js.map