import { useCallback } from "react";
import { toUserFacingAgentErrorMessage } from "../../services/agentErrorMessage";
import { normalizeServerExecutionStatus } from "../agentMessageHelpers";
export function useAgentRunCompletionSocketHandler(input) {
    const { actions, currentRunIdRef, lastSettledRunIdRef, lastNonHeartbeatUpdateAtRef, isWaitingRef, normalizeRunId, noteMissingRunId, settleCompletedRun, clearHeartbeatMessages, setError, setAgent, setLastRunStatusReason, setIsWaitingForResponse, setIsConnecting, setIsAgentThinking, } = input;
    return useCallback((messageType, payload) => {
        if (messageType === "agent:run:complete") {
            lastNonHeartbeatUpdateAtRef.current = Date.now();
            const completeRunId = payload?.runId;
            if (normalizeRunId(completeRunId) === null) {
                noteMissingRunId("agent:run:complete");
            }
            const finalStatus = normalizeServerExecutionStatus(payload?.finalStatus);
            const settledStatus = finalStatus === "cancelled" ? "cancelled" : "completed";
            settleCompletedRun(settledStatus, completeRunId);
            actions.settleRun({
                finalStatus: settledStatus,
                runId: completeRunId,
            });
            return true;
        }
        if (messageType !== "agent:run:error") {
            return false;
        }
        lastNonHeartbeatUpdateAtRef.current = Date.now();
        const errorRunId = normalizeRunId(payload?.runId);
        if (errorRunId === null) {
            noteMissingRunId("agent:run:error");
        }
        else if (lastSettledRunIdRef.current === errorRunId ||
            (currentRunIdRef.current !== null &&
                currentRunIdRef.current !== errorRunId)) {
            return true;
        }
        if (errorRunId !== null) {
            lastSettledRunIdRef.current = errorRunId;
        }
        const errorMessage = toUserFacingAgentErrorMessage(payload?.error) ||
            "AI could not complete this request.";
        clearHeartbeatMessages();
        setLastRunStatusReason(null);
        setError(errorMessage);
        setAgent((prev) => prev ? { ...prev, status: "error", statusMessage: errorMessage } : prev);
        setIsWaitingForResponse(false);
        isWaitingRef.current = false;
        setIsConnecting(false);
        setIsAgentThinking(false);
        return true;
    }, [
        actions,
        clearHeartbeatMessages,
        currentRunIdRef,
        isWaitingRef,
        lastNonHeartbeatUpdateAtRef,
        lastSettledRunIdRef,
        normalizeRunId,
        noteMissingRunId,
        setAgent,
        setError,
        setIsAgentThinking,
        setIsConnecting,
        setIsWaitingForResponse,
        setLastRunStatusReason,
        settleCompletedRun,
    ]);
}
//# sourceMappingURL=useAgentRunCompletionSocketHandler.js.map