import { useCallback, useEffect, useRef } from "react";
import { parseAgentStatus } from "../../services/agentStatus";
import { DIALOG_TYPES } from "../dialogs/agentDialogTypes";
import { loadAgentRunDiagnostics, replayAgentSessionDialog, } from "./useAgentSessionSync";
export function useAgentPendingDialogRecovery(input) {
    const { agentId, agentStatus, sessionId, activeInlineDialog, activeInlineDialogRef, terminalInstanceIdRef, appendToolUiEvent, recoverPendingDialog, } = input;
    const pendingDialogReplayCallbackIdsRef = useRef(new Set());
    const pendingDialogReplayTimeoutsRef = useRef(new Set());
    const schedulePendingDialogReplay = useCallback((targetAgentId, callbackId, dialogType) => {
        const normalizedCallbackId = callbackId.trim();
        if (!targetAgentId || !normalizedCallbackId) {
            return;
        }
        if (!sessionId) {
            appendToolUiEvent("ui:pending-dialog-replay-skipped", `${dialogType || "dialog"} callbackId=${normalizedCallbackId} agentId=${targetAgentId} reason=no-session`);
            return;
        }
        if (pendingDialogReplayCallbackIdsRef.current.has(normalizedCallbackId)) {
            return;
        }
        pendingDialogReplayCallbackIdsRef.current.add(normalizedCallbackId);
        const timeout = setTimeout(() => {
            pendingDialogReplayTimeoutsRef.current.delete(timeout);
            const activeCallbackId = activeInlineDialogRef.current?.request.callbackId?.trim();
            if (activeCallbackId === normalizedCallbackId) {
                return;
            }
            void replayAgentSessionDialog({
                callbackId: normalizedCallbackId,
                agentId: targetAgentId,
                reason: "frontend-recover",
                terminalInstanceId: terminalInstanceIdRef.current,
                sessionId,
            })
                .then((result) => {
                appendToolUiEvent("ui:pending-dialog-replay-requested", `${dialogType || "dialog"} callbackId=${normalizedCallbackId} agentId=${targetAgentId} replayed=${result.replayed ?? 0}`);
                if (!result.replayed) {
                    pendingDialogReplayCallbackIdsRef.current.delete(normalizedCallbackId);
                }
            })
                .catch((error) => {
                pendingDialogReplayCallbackIdsRef.current.delete(normalizedCallbackId);
                appendToolUiEvent("ui:pending-dialog-replay-failed", `${dialogType || "dialog"} callbackId=${normalizedCallbackId} agentId=${targetAgentId} error=${error instanceof Error ? error.message : String(error)}`);
            });
        }, 750);
        pendingDialogReplayTimeoutsRef.current.add(timeout);
    }, [
        activeInlineDialogRef,
        appendToolUiEvent,
        sessionId,
        terminalInstanceIdRef,
    ]);
    useEffect(() => {
        return () => {
            pendingDialogReplayTimeoutsRef.current.forEach((timeout) => clearTimeout(timeout));
            pendingDialogReplayTimeoutsRef.current.clear();
        };
    }, []);
    useEffect(() => {
        const currentStatus = parseAgentStatus(agentStatus);
        if (currentStatus !== "waitingForInput" ||
            activeInlineDialog ||
            !sessionId) {
            return;
        }
        let cancelled = false;
        appendToolUiEvent("ui:pending-dialog-recovery-check-started", `agentId=${agentId} status=${currentStatus} activeDialog=false`);
        void loadAgentRunDiagnostics(agentId, sessionId)
            .then((diagnostics) => {
            if (cancelled || activeInlineDialogRef.current)
                return;
            const pendingDialogs = diagnostics.pendingDialogs ?? [];
            const pendingDialog = pendingDialogs.find((dialog) => dialog.replayableToCurrentSession &&
                dialog.callbackId &&
                dialog.dialogType !== DIALOG_TYPES.CAPTURE_PAGE_DOM &&
                dialog.dialogType !== DIALOG_TYPES.CAPTURE_PAGE_SCREENSHOT);
            if (!pendingDialog) {
                appendToolUiEvent("ui:pending-dialog-recovery-check-not-required", `agentId=${agentId} pendingDialogCount=${diagnostics.pendingDialogCount ?? pendingDialogs.length} replayableDialogs=${pendingDialogs.length}`);
                return;
            }
            appendToolUiEvent("ui:pending-dialog-recovery-check-required", `${pendingDialog.dialogType} callbackId=${pendingDialog.callbackId} agentId=${agentId}`);
            if (recoverPendingDialog?.(pendingDialog)) {
                appendToolUiEvent("ui:pending-dialog-recovered-from-transcript", `${pendingDialog.dialogType} callbackId=${pendingDialog.callbackId} agentId=${agentId}`);
                return;
            }
            window.dispatchEvent(new CustomEvent("agent:dialog:recover", {
                detail: {
                    agentId,
                    callbackId: pendingDialog.callbackId,
                    dialogType: pendingDialog.dialogType,
                    terminalInstanceId: terminalInstanceIdRef.current,
                },
            }));
            schedulePendingDialogReplay(agentId, pendingDialog.callbackId, pendingDialog.dialogType);
        })
            .catch((error) => {
            appendToolUiEvent("ui:pending-dialog-recovery-lookup-failed", error instanceof Error ? error.message : String(error));
        });
        return () => {
            cancelled = true;
        };
    }, [
        activeInlineDialog,
        activeInlineDialogRef,
        agentId,
        agentStatus,
        appendToolUiEvent,
        recoverPendingDialog,
        schedulePendingDialogReplay,
        sessionId,
        terminalInstanceIdRef,
    ]);
    return { schedulePendingDialogReplay };
}
//# sourceMappingURL=useAgentPendingDialogRecovery.js.map