import { useEffect } from "react";
import { applyToolApprovalResolvedToTranscript } from "./agentSessionState";
export function useAgentToolApprovalResolvedEvents(input) {
    const { agentIdRef, agentStubIdRef, messagesRef, actions, isWaitingRef, setIsWaitingForResponse, setIsAgentThinking, } = input;
    useEffect(() => {
        const onApprovalResolved = (event) => {
            try {
                const detail = event?.detail || {};
                const eventAgentId = detail.agentId;
                if (eventAgentId) {
                    const myStubId = agentStubIdRef.current;
                    const myAgentId = agentIdRef.current;
                    if (eventAgentId !== myStubId && eventAgentId !== myAgentId) {
                        return;
                    }
                }
                const messageId = detail.messageId;
                const toolCallId = detail.toolCallId;
                const approved = !!detail.approved;
                console.log("[AgentTerminal] Approval resolved:", {
                    messageId,
                    toolCallId,
                    approved,
                });
                if (!messageId || !toolCallId)
                    return;
                const currentMessages = messagesRef.current || [];
                const hasMatchingToolCall = currentMessages.some((message) => (message.toolCalls || []).some((toolCall) => toolCall.toolCallId === toolCallId));
                if (!hasMatchingToolCall) {
                    return;
                }
                messagesRef.current = applyToolApprovalResolvedToTranscript(messagesRef.current, {
                    messageId,
                    toolCallId,
                    approved,
                });
                actions.toolApprovalResolved({
                    messageId,
                    toolCallId,
                    approved,
                });
                console.log("[AgentTerminal] Setting isAgentThinking=true after approval");
                setIsWaitingForResponse(true);
                isWaitingRef.current = true;
                setIsAgentThinking(true);
            }
            catch (error) {
                console.error("Error handling approval resolution:", error);
            }
        };
        window.addEventListener("agent:toolApprovalResolved", onApprovalResolved);
        return () => {
            window.removeEventListener("agent:toolApprovalResolved", onApprovalResolved);
        };
    }, [
        actions,
        agentIdRef,
        agentStubIdRef,
        isWaitingRef,
        messagesRef,
        setIsAgentThinking,
        setIsWaitingForResponse,
    ]);
}
//# sourceMappingURL=useAgentToolApprovalResolvedEvents.js.map