import { useCallback } from "react";
import { clearStaleRunningLoadSuppression, hasStaleRunningLoadSuppression, loadAgentSessionSnapshot, } from "./useAgentSessionSync";
import { isAgentNotFoundLoadError } from "./useAgentLoadErrorHandler";
import { getLoadedCostLimitExceeded } from "./agentSessionCostLimit";
import { buildLoadedContextWindowStatus, mergeLoadedAgentTranscript, parseLoadedAgentMetadata, } from "./agentSessionSnapshot";
export function useAgentLoader(input) {
    const { agentStub, actions, messagesRef, seenMessageIdsRef, isStoppingRef, initializeDraftAgent, syncLoadedRunState, sanitizeAgentMetadata, handleLoadError, setAgent, setAgentMetadata, setError, } = input;
    return useCallback(async ({ silent = false } = {}) => {
        try {
            if (initializeDraftAgent()) {
                return;
            }
            if (!silent) {
                actions.startLoading();
            }
            setError(null);
            const { agent: agentData, queuedPrompts: prompts } = await loadAgentSessionSnapshot(agentStub.id);
            const serverReturnedRunning = agentData.status === "running" || agentData.status === 1;
            const hasSuppressedRunningLoad = hasStaleRunningLoadSuppression(agentStub.id);
            const isStaleRunningLoadDuringStop = serverReturnedRunning &&
                (isStoppingRef.current || hasSuppressedRunningLoad);
            if (!serverReturnedRunning) {
                clearStaleRunningLoadSuppression(agentStub.id);
            }
            const loadedAgentForUi = isStaleRunningLoadDuringStop
                ? { ...agentData, status: "idle", statusMessage: undefined }
                : agentData;
            setAgent(loadedAgentForUi);
            actions.replaceQueuedPrompts(prompts);
            const { merged, isRunning, waitingForApproval, waitingForInput, hasStreaming, } = mergeLoadedAgentTranscript({
                agentData,
                localMessages: messagesRef.current,
                markSeenMessageId: (messageId) => {
                    seenMessageIdsRef.current.add(messageId.toLowerCase());
                },
            });
            messagesRef.current = merged;
            actions.replaceTranscript(merged);
            syncLoadedRunState({
                isRunning,
                waitingForApproval,
                waitingForInput,
                hasStreaming,
            });
            const loadedCostLimitExceeded = getLoadedCostLimitExceeded(agentData);
            if (loadedCostLimitExceeded) {
                actions.replaceCostLimitExceeded(loadedCostLimitExceeded);
            }
            const sanitizedLoadedMetadata = sanitizeAgentMetadata(parseLoadedAgentMetadata(agentData));
            setAgentMetadata(sanitizedLoadedMetadata);
            const loadedContextWindowStatus = buildLoadedContextWindowStatus(agentData);
            actions.applySnapshot({
                agent: { ...loadedAgentForUi, messages: merged },
                queuedPrompts: prompts,
                metadata: sanitizedLoadedMetadata,
                contextWindowStatus: loadedContextWindowStatus,
            });
        }
        catch (error) {
            if (!isAgentNotFoundLoadError(error)) {
                console.error("Failed to load agent:", error);
            }
            handleLoadError(error);
        }
    }, [
        actions,
        agentStub.id,
        handleLoadError,
        initializeDraftAgent,
        isStoppingRef,
        messagesRef,
        sanitizeAgentMetadata,
        seenMessageIdsRef,
        setAgent,
        setAgentMetadata,
        setError,
        syncLoadedRunState,
    ]);
}
//# sourceMappingURL=useAgentLoader.js.map