import { useCallback } from "react";
import { applyAssistantContentChunkToTranscript } from "./agentSessionState";
import { contextWindowStatusFromStreamCost, hasNonZeroLiveTotals, liveTotalsFromStreamCost, } from "./agentSessionLiveTotals";
export function useAgentContentChunkHandler(input) {
    const { agent, actions, messagesRef, isWaitingRef, shouldCreateNewMessageRef, setIsWaitingForResponse, setIsAgentThinking, createNewStreamMessage, } = input;
    return useCallback((message, agentData) => {
        const messageId = message.data?.messageId;
        if (!messageId) {
            console.error("[AgentTerminal] Backend invariant violation: content chunk arrived without messageId. Dropping.", {
                agentId: agentData?.id,
                isIncremental: message.data?.isIncremental,
                previousContentLength: message.data?.previousContentLength,
                totalContentLength: message.data?.totalContentLength,
            });
            return;
        }
        setIsWaitingForResponse(false);
        isWaitingRef.current = false;
        if (message.data?.deltaContent) {
            setIsAgentThinking(false);
        }
        const cost = message.cost;
        const nextTotals = liveTotalsFromStreamCost(cost);
        if (nextTotals) {
            if (hasNonZeroLiveTotals(nextTotals)) {
                actions.replaceLiveTotals(nextTotals);
            }
            if (cost &&
                cost.limit &&
                cost.total &&
                Number(cost.total) > Number(cost.limit)) {
                actions.replaceCostLimitExceeded({
                    totalCost: Number(cost.total),
                    costLimit: Number(cost.limit),
                    initialCostLimit: Number(cost.limit),
                });
                setIsWaitingForResponse(false);
                shouldCreateNewMessageRef.current = false;
            }
            const contextWindowStatus = contextWindowStatusFromStreamCost(cost, agentData?.model || agent?.model || "");
            if (contextWindowStatus) {
                actions.replaceContextWindowStatus(contextWindowStatus);
            }
        }
        const contentChunk = {
            messageId,
            deltaContent: message.data?.deltaContent,
            reasoning: message.data?.reasoning,
            isIncremental: message.data?.isIncremental,
            previousContentLength: message.data?.previousContentLength,
            totalContentLength: message.data?.totalContentLength,
            createMessage: () => createNewStreamMessage(messageId, agentData),
        };
        const currentMessages = messagesRef.current;
        const existingMessageIndex = currentMessages.findIndex((msg) => msg.id === messageId);
        const previousContentLength = message.data?.previousContentLength || 0;
        if (existingMessageIndex === -1) {
            if (message.data?.isIncremental && previousContentLength > 0) {
                console.warn("[AgentTerminal] Incremental chunk arrived before its base message existed", {
                    messageId,
                    previousContentLength,
                    totalContentLength: message.data?.totalContentLength,
                    deltaLength: (message.data?.deltaContent || "").length,
                });
            }
        }
        else {
            const existingMessage = currentMessages[existingMessageIndex];
            const currentContentLength = existingMessage?.content?.length || 0;
            const totalContentLength = message.data?.totalContentLength || 0;
            if (message.data?.isIncremental &&
                previousContentLength !== currentContentLength &&
                (previousContentLength > 0 || currentContentLength > 0)) {
                console.warn("[AgentTerminal] Content chunk length mismatch", {
                    messageId,
                    previousContentLength,
                    currentContentLength,
                    totalContentLength,
                    deltaLength: (message.data?.deltaContent || "").length,
                });
            }
        }
        messagesRef.current = applyAssistantContentChunkToTranscript(currentMessages, contentChunk);
        actions.assistantContentChunk(contentChunk);
    }, [
        actions,
        agent?.model,
        createNewStreamMessage,
        isWaitingRef,
        messagesRef,
        setIsAgentThinking,
        setIsWaitingForResponse,
        shouldCreateNewMessageRef,
    ]);
}
//# sourceMappingURL=useAgentContentChunkHandler.js.map