import { useCallback } from "react";
import { extractToolCallFields } from "../agentMessageConversion";
import { applyToolResultForMessageInTranscript } from "./agentSessionState";
import { contextWindowStatusFromStreamCost, hasNonZeroLiveTotals, liveTotalsFromStreamCost, liveTotalsFromToolResultData, } from "./agentSessionLiveTotals";
export function useAgentToolResultHandler(input) {
    const { agent, actions, messagesRef, shouldCreateNewMessageRef, appendToolUiEvent, } = input;
    return useCallback((message, agentData) => {
        const extractedToolCall = extractToolCallFields(message.data);
        const resultToolCallId = extractedToolCall.toolCallId || crypto.randomUUID();
        const resultMessageId = message.data?.messageId;
        if (!resultMessageId) {
            console.error("[AgentTerminal] Backend invariant violation: tool result arrived without messageId. Dropping.", {
                agentId: agentData?.id,
                toolCallId: resultToolCallId,
                toolName: message.data?.functionName || message.data?.displayName,
            });
            return;
        }
        const cost = message.cost;
        const nextTotals = liveTotalsFromStreamCost(cost);
        if (nextTotals) {
            if (hasNonZeroLiveTotals(nextTotals)) {
                actions.replaceLiveTotals(nextTotals);
            }
            const contextWindowStatus = contextWindowStatusFromStreamCost(cost, agentData?.model || agent?.model || "");
            if (contextWindowStatus) {
                actions.replaceContextWindowStatus(contextWindowStatus);
            }
        }
        else {
            const dataTotals = liveTotalsFromToolResultData(message.data);
            if (dataTotals && hasNonZeroLiveTotals(dataTotals)) {
                actions.replaceLiveTotals(dataTotals);
            }
        }
        appendToolUiEvent("ui:tool-result-targeted", `${extractedToolCall.functionName || "unknown"} toolCallId=${resultToolCallId} targetMessageId=${resultMessageId}`);
        if (!message.data) {
            return;
        }
        const fallbackToolCallCreatedDate = message.data.createdDate ||
            message.timestamp ||
            new Date().toISOString();
        const fallbackToolCall = {
            id: resultToolCallId,
            messageId: resultMessageId,
            toolCallId: resultToolCallId,
            functionName: extractedToolCall.functionName,
            functionArguments: extractedToolCall.functionArguments,
            functionResult: message.data.functionResult || message.data.result || "",
            functionResultRichContent: message.data.richContent || undefined,
            functionError: message.data.functionError || message.data.error || "",
            isCompleted: true,
            responseTimeMs: message.data.responseTimeMs,
            createdDate: fallbackToolCallCreatedDate,
        };
        const targetIndex = messagesRef.current.findIndex((message) => message.id === resultMessageId);
        if (targetIndex < 0) {
            appendToolUiEvent("ui:tool-result-dropped", `${extractedToolCall.functionName || "unknown"} toolCallId=${resultToolCallId} reason=no-target-row`);
            return;
        }
        const appliedToolResult = applyToolResultForMessageInTranscript(messagesRef.current, {
            messageId: resultMessageId,
            toolCallId: resultToolCallId,
            fallbackToolCall,
        });
        if (appliedToolResult.allToolCallsCompleted) {
            shouldCreateNewMessageRef.current = true;
        }
        messagesRef.current = appliedToolResult.transcript;
        actions.toolResult({
            messageId: resultMessageId,
            toolCallId: resultToolCallId,
            fallbackToolCall,
        });
        const messageWithToolResult = messagesRef.current[targetIndex];
        const matchingToolCall = messageWithToolResult?.toolCalls?.find((tc) => tc.toolCallId === resultToolCallId);
        appendToolUiEvent("ui:tool-result-applied", `${extractedToolCall.functionName || "unknown"} toolCallId=${resultToolCallId} targetMessageId=${messageWithToolResult?.id || resultMessageId} completed=${matchingToolCall?.isCompleted ? "yes" : "no"} messageToolCalls=${messageWithToolResult?.toolCalls?.length || 0}`);
    }, [
        actions,
        agent?.model,
        appendToolUiEvent,
        messagesRef,
        shouldCreateNewMessageRef,
    ]);
}
//# sourceMappingURL=useAgentToolResultHandler.js.map