import { useCallback } from "react";
import { mergeResyncedAssistantMessage } from "./agentSessionState";
export function useAgentRunResyncSocketHandler(input) {
    const { agent, actions, messagesRef, currentRunIdRef, lastSeqRef, lastResyncedMessageIdsRef, normalizeRunId, noteMissingRunId, appendToolUiEvent, createNewStreamMessage, } = input;
    return useCallback((messageType, payload) => {
        if (messageType !== "agent:run:resync") {
            return false;
        }
        const resyncRunId = normalizeRunId(payload?.runId);
        if (resyncRunId === null) {
            noteMissingRunId("agent:run:resync");
        }
        else if (currentRunIdRef.current !== null &&
            resyncRunId !== currentRunIdRef.current) {
            appendToolUiEvent("ui:stream-runid-dropped", `agent:run:resync runId=${resyncRunId} currentRunId=${currentRunIdRef.current}`);
            return true;
        }
        const resyncMessageId = payload?.messageId;
        if (!resyncMessageId) {
            return true;
        }
        const totalContent = String(payload?.totalContent ?? "");
        const reasoning = String(payload?.reasoning ?? "");
        const seq = Number(payload?.seq ?? 0);
        const rawToolCalls = Array.isArray(payload?.toolCalls)
            ? payload.toolCalls
            : [];
        const droppedIdlessToolNames = [];
        const normalizedToolCalls = rawToolCalls
            .filter((toolCall) => toolCall && typeof toolCall === "object")
            .flatMap((toolCall) => {
            // Never synthesize an id for resynced tool calls: an invented id can
            // never match the persisted toolCallId, so the same call would
            // render twice once the DB copy merges into the transcript.
            const toolCallId = toolCall.toolCallId || toolCall.id;
            if (!toolCallId) {
                droppedIdlessToolNames.push(String(toolCall.functionName ||
                    toolCall.name ||
                    toolCall.displayName ||
                    "unknown"));
                return [];
            }
            return {
                id: toolCallId,
                messageId: resyncMessageId,
                toolCallId,
                functionName: toolCall.functionName ||
                    toolCall.name ||
                    toolCall.displayName ||
                    "",
                functionArguments: toolCall.functionArguments ?? toolCall.arguments ?? "",
                functionResult: toolCall.functionResult ?? toolCall.result ?? "",
                functionResultRichContent: toolCall.functionResultRichContent ??
                    toolCall.richContent ??
                    undefined,
                functionError: toolCall.functionError ?? toolCall.error ?? "",
                isCompleted: toolCall.isCompleted === true,
                responseTimeMs: toolCall.responseTimeMs,
                createdDate: toolCall.createdDate ||
                    payload?.timestamp ||
                    new Date().toISOString(),
                requiresApproval: toolCall.requiresApproval,
                ...(toolCall.dbMessageId
                    ? { dbMessageId: toolCall.dbMessageId }
                    : {}),
            };
        });
        if (droppedIdlessToolNames.length > 0) {
            appendToolUiEvent("ui:resync-tool-calls-dropped", `messageId=${resyncMessageId} reason=no-tool-call-id tools=${droppedIdlessToolNames.join(",")}`);
        }
        const existingIndex = messagesRef.current.findIndex((message) => message.id === resyncMessageId);
        if (existingIndex === -1) {
            const created = createNewStreamMessage(resyncMessageId, agent);
            const seeded = {
                ...created,
                content: totalContent,
                reasoning,
                toolCalls: normalizedToolCalls,
            };
            const updated = [...messagesRef.current, seeded];
            messagesRef.current = updated;
            actions.replaceTranscript(updated);
            return true;
        }
        else {
            const updated = messagesRef.current.map((message, index) => index === existingIndex
                ? mergeResyncedAssistantMessage(message, {
                    content: totalContent,
                    reasoning,
                    toolCalls: normalizedToolCalls,
                })
                : message);
            messagesRef.current = updated;
            actions.replaceTranscript(updated);
        }
        if (seq && seq > lastSeqRef.current) {
            lastSeqRef.current = seq;
        }
        actions.runFrame({
            runId: payload?.runId,
            seq,
        });
        lastResyncedMessageIdsRef.current.add(resyncMessageId.toLowerCase());
        return true;
    }, [
        actions,
        agent,
        appendToolUiEvent,
        createNewStreamMessage,
        currentRunIdRef,
        lastResyncedMessageIdsRef,
        lastSeqRef,
        messagesRef,
        normalizeRunId,
        noteMissingRunId,
    ]);
}
//# sourceMappingURL=useAgentRunResyncSocketHandler.js.map