import { useEffect, useMemo, useReducer, useRef } from "react";
import { buildPlaceholderAgentDetails } from "../agentMessageHelpers";
import { applyBackendSnapshot, acceptRunFrame, addOptimisticUserMessage, applyAssistantContentChunkToTranscript, applyHeartbeatMessageToTranscript, applyOperationHistory, applyQueuedPromptAdded, applyQueuedPromptProcessed, applyRunStart, applyRunStatus, applySnapshotError, applySnapshotLoading, applySnapshotReady, applyToolResultForMessageInTranscript, applyToolApprovalsRequired, applyToolApprovalResolved, clearHeartbeatMessagesFromTranscript, completeOpenAssistantMessagesInTranscript, completeOpenStreamingMessagesInTranscript, armStopGuard, clearStopGuard, createInitialAgentSessionState, reconcileServerUserMessage, replaceOperationHistory, replaceTranscript, replaceQueuedPrompts, removeOptimisticUserMessage, settleCompletedRun, upsertToolCallForMessageInTranscript, } from "./agentSessionState";
function reducer(state, action) {
    switch (action.type) {
        case "reset":
            return action.state;
        case "loading":
            return applySnapshotLoading(state);
        case "ready":
            return applySnapshotReady(state);
        case "error":
            return applySnapshotError(state, action.error);
        case "replaceError":
            return { ...state, error: action.error };
        case "snapshot":
            return applyBackendSnapshot(state, action.snapshot);
        case "replaceAgent":
            return { ...state, agent: action.agent };
        case "replaceMetadata":
            return { ...state, metadata: action.metadata };
        case "replaceCostLimitExceeded":
            return { ...state, costLimitExceeded: action.costLimitExceeded };
        case "replaceContextWindowStatus":
            return { ...state, contextWindowStatus: action.contextWindowStatus };
        case "replaceLiveTotals":
            return { ...state, liveTotals: action.liveTotals };
        case "setBrowserClaimMutationPending":
            return { ...state, browserClaimMutationPending: action.isPending };
        case "setActiveInlineDialog":
            return { ...state, activeInlineDialog: action.activeInlineDialog };
        case "patchRunState":
            return { ...state, run: { ...state.run, ...action.run } };
        case "replaceQueuedPrompts":
            return replaceQueuedPrompts(state, action.queuedPrompts);
        case "addQueuedPrompt":
            return applyQueuedPromptAdded(state, action.queuedPrompt);
        case "processQueuedPrompt":
            return applyQueuedPromptProcessed(state, action.promptId);
        case "mergeOperationHistory":
            return applyOperationHistory(state, action.operations);
        case "replaceOperationHistory":
            return replaceOperationHistory(state, action.operations);
        case "addOptimisticUserMessage":
            return addOptimisticUserMessage(state, action.message);
        case "removeOptimisticUserMessage":
            return removeOptimisticUserMessage(state, action.messageId);
        case "replaceTranscript":
            return replaceTranscript(state, action.transcript);
        case "assistantContentChunk":
            return {
                ...state,
                transcript: applyAssistantContentChunkToTranscript(state.transcript, action.chunk),
            };
        case "heartbeatMessage":
            return {
                ...state,
                transcript: applyHeartbeatMessageToTranscript(state.transcript, action.message),
            };
        case "clearHeartbeatMessages":
            return {
                ...state,
                transcript: clearHeartbeatMessagesFromTranscript(state.transcript),
            };
        case "completeOpenAssistantMessages":
            return {
                ...state,
                transcript: completeOpenAssistantMessagesInTranscript(state.transcript),
            };
        case "completeOpenStreamingMessages":
            return {
                ...state,
                transcript: completeOpenStreamingMessagesInTranscript(state.transcript),
            };
        case "toolCall":
            return {
                ...state,
                transcript: upsertToolCallForMessageInTranscript(state.transcript, action.input),
            };
        case "toolResult":
            return {
                ...state,
                transcript: applyToolResultForMessageInTranscript(state.transcript, action.input).transcript,
            };
        case "reconcileServerUserMessage":
            return reconcileServerUserMessage(state, action.echo);
        case "runStart":
            return applyRunStart(state, action.input);
        case "runFrame":
            return acceptRunFrame(state, action.input);
        case "runStatus":
            return applyRunStatus(state, action.status, action.reason ?? null);
        case "armStopGuard":
            return armStopGuard(state);
        case "clearStopGuard":
            return clearStopGuard(state);
        case "settleRun":
            return settleCompletedRun(state, action.input);
        case "toolApprovalsRequired":
            return applyToolApprovalsRequired(state, action.input);
        case "toolApprovalResolved":
            return applyToolApprovalResolved(state, action.resolution);
        default:
            return state;
    }
}
export function useAgentSession(input) {
    const initialState = useMemo(() => createInitialAgentSessionState({
        agent: buildPlaceholderAgentDetails(input.agentStub),
        isLoading: input.agentStub.status !== "new",
    }), [input.agentStub.id]);
    const [state, dispatch] = useReducer(reducer, initialState);
    const commandHandlersRef = useRef({});
    useEffect(() => {
        dispatch({ type: "reset", state: initialState });
    }, [initialState]);
    const commands = useMemo(() => ({
        reload: async (options) => commandHandlersRef.current.reload?.(options),
        submitPrompt: async (input) => commandHandlersRef.current.submitPrompt?.(input),
        sendQuickMessage: async (text) => commandHandlersRef.current.sendQuickMessage?.(text),
        stopRun: async () => commandHandlersRef.current.stopRun?.(),
        resolveToolApproval: async (input) => commandHandlersRef.current.resolveToolApproval?.(input),
        cancelInlineDialog: () => commandHandlersRef.current.cancelInlineDialog?.(),
        refreshContext: async () => commandHandlersRef.current.refreshContext?.(),
        claimBrowser: async (takeOver) => commandHandlersRef.current.claimBrowser?.(takeOver),
        releaseBrowser: async () => commandHandlersRef.current.releaseBrowser?.(),
    }), []);
    const bindCommands = useMemo(() => (nextCommands) => {
        commandHandlersRef.current = {
            ...commandHandlersRef.current,
            ...nextCommands,
        };
    }, []);
    const actions = useMemo(() => ({
        startLoading: () => dispatch({ type: "loading" }),
        finishReady: () => dispatch({ type: "ready" }),
        applySnapshot: (snapshot) => dispatch({ type: "snapshot", snapshot }),
        applyError: (error) => dispatch({ type: "error", error }),
        replaceError: (error) => dispatch({ type: "replaceError", error }),
        replaceAgent: (agent) => dispatch({ type: "replaceAgent", agent }),
        replaceMetadata: (metadata) => dispatch({ type: "replaceMetadata", metadata }),
        replaceCostLimitExceeded: (costLimitExceeded) => dispatch({ type: "replaceCostLimitExceeded", costLimitExceeded }),
        replaceContextWindowStatus: (contextWindowStatus) => dispatch({ type: "replaceContextWindowStatus", contextWindowStatus }),
        replaceLiveTotals: (liveTotals) => dispatch({ type: "replaceLiveTotals", liveTotals }),
        setBrowserClaimMutationPending: (isPending) => dispatch({ type: "setBrowserClaimMutationPending", isPending }),
        setActiveInlineDialog: (activeInlineDialog) => dispatch({ type: "setActiveInlineDialog", activeInlineDialog }),
        patchRunState: (run) => dispatch({ type: "patchRunState", run }),
        replaceQueuedPrompts: (queuedPrompts) => dispatch({ type: "replaceQueuedPrompts", queuedPrompts }),
        addQueuedPrompt: (queuedPrompt) => dispatch({ type: "addQueuedPrompt", queuedPrompt }),
        processQueuedPrompt: (promptId) => dispatch({ type: "processQueuedPrompt", promptId }),
        mergeOperationHistory: (operations) => dispatch({ type: "mergeOperationHistory", operations }),
        replaceOperationHistory: (operations) => dispatch({ type: "replaceOperationHistory", operations }),
        addOptimisticUserMessage: (message) => dispatch({ type: "addOptimisticUserMessage", message }),
        removeOptimisticUserMessage: (messageId) => dispatch({ type: "removeOptimisticUserMessage", messageId }),
        replaceTranscript: (transcript) => dispatch({ type: "replaceTranscript", transcript }),
        assistantContentChunk: (chunk) => dispatch({ type: "assistantContentChunk", chunk }),
        heartbeatMessage: (message) => dispatch({ type: "heartbeatMessage", message }),
        clearHeartbeatMessages: () => dispatch({ type: "clearHeartbeatMessages" }),
        completeOpenAssistantMessages: () => dispatch({ type: "completeOpenAssistantMessages" }),
        completeOpenStreamingMessages: () => dispatch({ type: "completeOpenStreamingMessages" }),
        toolCall: (input) => dispatch({ type: "toolCall", input }),
        toolResult: (input) => dispatch({ type: "toolResult", input }),
        reconcileServerUserMessage: (echo) => dispatch({ type: "reconcileServerUserMessage", echo }),
        runStart: (input) => dispatch({ type: "runStart", input }),
        runFrame: (input) => dispatch({ type: "runFrame", input }),
        runStatus: (status, reason) => dispatch({ type: "runStatus", status, reason }),
        armStopGuard: () => dispatch({ type: "armStopGuard" }),
        clearStopGuard: () => dispatch({ type: "clearStopGuard" }),
        settleRun: (input) => dispatch({ type: "settleRun", input }),
        toolApprovalsRequired: (input) => dispatch({ type: "toolApprovalsRequired", input }),
        toolApprovalResolved: (resolution) => dispatch({ type: "toolApprovalResolved", resolution }),
    }), []);
    return { state, commands, bindCommands, actions };
}
//# sourceMappingURL=useAgentSession.js.map