import { useCallback } from "react";
import { flushSync } from "react-dom";
import { extractToolCallFields } from "../agentMessageConversion";
import { upsertToolCallForMessageInTranscript } from "./agentSessionState";
export function useAgentToolCallHandler(input) {
    const { actions, messagesRef, appendToolUiEvent, setIsAgentThinking, createNewStreamMessage, } = input;
    return useCallback((message, agentData) => {
        const extractedToolCall = extractToolCallFields(message.data);
        const toolCallId = extractedToolCall.toolCallId || crypto.randomUUID();
        const toolCallMessageId = message.data?.messageId;
        if (!toolCallMessageId || !message.data) {
            console.error("[AgentTerminal] Backend invariant violation: tool call arrived without messageId. Dropping.", {
                agentId: agentData?.id,
                toolCallId,
                toolName: message.data?.name || message.data?.displayName,
            });
            return;
        }
        appendToolUiEvent("ui:tool-call-targeted", `${extractedToolCall.functionName || "unknown"} toolCallId=${toolCallId} targetMessageId=${toolCallMessageId} providedMessageId=${String(message.data?.messageId || "none")}`);
        const toolCallError = message.data.functionError || message.data.error || "";
        const isPruned = !!message.data?.isPruned || /^PRUNED$/i.test(String(toolCallError));
        const toolCallCreatedDate = message.data.createdDate ||
            message.timestamp ||
            new Date().toISOString();
        const toolCallState = String(message.data?.state || "").toLowerCase();
        const isExplicitApprovalRequired = toolCallState === "toolapprovalsrequired" ||
            toolCallState === "waitingforapproval";
        const requiresApproval = isExplicitApprovalRequired
            ? message.data?.requiresApproval
            : undefined;
        const incomingToolCall = {
            id: toolCallId,
            messageId: toolCallMessageId,
            dbMessageId: message.data.messageId,
            toolCallId: toolCallId,
            functionName: extractedToolCall.functionName,
            functionArguments: extractedToolCall.functionArguments,
            functionResult: message.data.functionResult || message.data.result || "",
            functionResultRichContent: message.data.richContent || undefined,
            functionError: toolCallError,
            isPruned,
            isCompleted: false,
            responseTimeMs: message.data.responseTimeMs,
            createdDate: toolCallCreatedDate,
            requiresApproval,
        };
        flushSync(() => {
            messagesRef.current = upsertToolCallForMessageInTranscript(messagesRef.current, {
                messageId: toolCallMessageId,
                toolCall: incomingToolCall,
                createMessage: () => createNewStreamMessage(toolCallMessageId, agentData),
            });
            actions.toolCall({
                messageId: toolCallMessageId,
                toolCall: incomingToolCall,
                createMessage: () => createNewStreamMessage(toolCallMessageId, agentData),
            });
        });
        const messageWithToolCall = messagesRef.current.find((msg) => msg.id === toolCallMessageId);
        appendToolUiEvent("ui:tool-call-attached", `${extractedToolCall.functionName || "unknown"} toolCallId=${toolCallId} targetMessageId=${toolCallMessageId} messageToolCalls=${messageWithToolCall?.toolCalls?.length || 0} assistantMessages=${messagesRef.current.filter((msg) => msg.role === "assistant").length}`);
        if (requiresApproval) {
            setIsAgentThinking(false);
        }
    }, [
        actions,
        appendToolUiEvent,
        createNewStreamMessage,
        messagesRef,
        setIsAgentThinking,
    ]);
}
//# sourceMappingURL=useAgentToolCallHandler.js.map