import { useCallback } from "react";
import { buildQuestionnaireDialogFromTranscript } from "./agentQuestionnaireTranscriptRecovery";
import { submitAgentSessionDialogResponse } from "./useAgentSessionSync";
export function useAgentQuestionnaireDialogRecovery(input) {
    const { messagesRef, agentId, sessionId, setActiveInlineDialog, appendToolUiEvent, onInteractionSubmitted, } = input;
    return useCallback((pendingDialog) => {
        const recovered = buildQuestionnaireDialogFromTranscript({
            messages: messagesRef.current,
            pendingDialog,
            agentId,
        });
        if (!recovered || !sessionId) {
            return false;
        }
        // Mark the dialog resolved once the backend accepts the response so a racing
        // recovery cannot re-materialize it as a fresh empty questionnaire. Only on
        // success — a failed submit leaves it eligible for a genuine re-show.
        const markResolved = () => {
            window.dispatchEvent(new CustomEvent("agent:dialog:resolved", {
                detail: { callbackId: recovered.request.callbackId },
            }));
        };
        setActiveInlineDialog({
            request: recovered.request,
            onComplete: (result) => {
                void submitAgentSessionDialogResponse({
                    callbackId: recovered.request.callbackId,
                    sessionId,
                    cancelled: false,
                    resultJson: JSON.stringify(result),
                })
                    .then(markResolved)
                    .catch((error) => {
                    appendToolUiEvent("ui:pending-dialog-response-submit-failed", error instanceof Error ? error.message : String(error));
                });
                void Promise.resolve(onInteractionSubmitted?.());
            },
            onCancel: () => {
                void submitAgentSessionDialogResponse({
                    callbackId: recovered.request.callbackId,
                    sessionId,
                    cancelled: true,
                })
                    .then(markResolved)
                    .catch((error) => {
                    appendToolUiEvent("ui:pending-dialog-cancel-submit-failed", error instanceof Error ? error.message : String(error));
                });
                void Promise.resolve(onInteractionSubmitted?.());
            },
        });
        return true;
    }, [
        agentId,
        appendToolUiEvent,
        messagesRef,
        onInteractionSubmitted,
        sessionId,
        setActiveInlineDialog,
    ]);
}
//# sourceMappingURL=useAgentQuestionnaireDialogRecovery.js.map