import { useCallback, useEffect, useRef, } from "react";
import { clearStaleRunningLoadSuppression, pushQueuedPromptSessionRun, startAgentSessionRun, } from "./useAgentSessionSync";
import { createOptimisticUserMessage } from "./agentSessionState";
import { hasPromptPlaceholders } from "./agentPromptPlaceholders";
import { createTempAgentMessageId } from "./agentOptimisticMessage";
import { createAgentStartRequest } from "./agentStartRequest";
import { getSubmitErrorMessage } from "./agentSubmitErrors";
export function useAgentSubmitHandlers(input) {
    const { readOnly, isSubmitting, isStopGuardActive = false, editContext, agent, agentStub, prompt, activePlaceholderInput, allPlaceholdersFilled, placeholderInputRef, promptPlaceholderInputRef, shouldSubmitFilledPlaceholderInputRef, activeInlineDialogRef, isWaitingRef, lastNonHeartbeatUpdateAtRef, clearStopGuard, supersedePendingApprovals, hasPendingApprovals, registerSuppressedQueuedPrompt, clearSuppressedQueuedPrompt, cancelActiveInlineDialog, addOptimisticTranscriptMessage, removeOptimisticTranscriptMessage, getStagedAttachments, clearStagedAttachments, getPendingRequestSettings, buildSubmitContext, handleSubmitResponse, persistPendingSettingsIfNeeded, onInteractionSubmitted, clearSuggestion, setError, setPrompt, setIsSubmitting, setIsWaitingForResponse, setIsAgentThinking, setShouldAutoScroll, setPromptHistory, setCurrentHistoryIndex, } = input;
    const submitInFlightRef = useRef(false);
    useEffect(() => {
        if (!isSubmitting) {
            submitInFlightRef.current = false;
        }
    }, [isSubmitting]);
    const handleSubmit = useCallback(async (promptOverride) => {
        const hasPromptOverride = promptOverride !== undefined;
        if (readOnly) {
            console.warn("[AgentTerminal] handleSubmit blocked: read-only access");
            return;
        }
        if (isStopGuardActive) {
            console.warn("[AgentTerminal] handleSubmit blocked: agent is stopping");
            setError("The agent is stopping. Wait a moment before sending again.");
            return;
        }
        if (isSubmitting || submitInFlightRef.current) {
            console.warn("[AgentTerminal] handleSubmit blocked: already submitting");
            return;
        }
        submitInFlightRef.current = true;
        if (!(await supersedePendingApprovals())) {
            submitInFlightRef.current = false;
            return;
        }
        if (!editContext) {
            console.error("[AgentTerminal] handleSubmit blocked: editContext is undefined");
            setError("Editor context not available. Please refresh the page.");
            submitInFlightRef.current = false;
            return;
        }
        if (!hasPromptOverride &&
            activePlaceholderInput &&
            allPlaceholdersFilled) {
            const placeholderInput = placeholderInputRef.current;
            if (!placeholderInput) {
                submitInFlightRef.current = false;
                return;
            }
            shouldSubmitFilledPlaceholderInputRef.current = true;
            submitInFlightRef.current = false;
            placeholderInput.submit();
            return;
        }
        if (!hasPromptOverride &&
            prompt &&
            hasPromptPlaceholders(prompt) &&
            allPlaceholdersFilled) {
            const promptPlaceholderInput = promptPlaceholderInputRef.current;
            submitInFlightRef.current = false;
            promptPlaceholderInput?.submit();
            return;
        }
        const savedPrompt = (promptOverride ?? prompt).trim();
        const stagedAttachments = getStagedAttachments?.() ?? [];
        const isNewAgent = agentStub.status === "new" || agent?.status === "new";
        if (!savedPrompt && stagedAttachments.length === 0 && !isNewAgent) {
            console.warn("[AgentTerminal] handleSubmit blocked: empty prompt");
            submitInFlightRef.current = false;
            return;
        }
        const agentId = agent?.id || agentStub.id;
        if (!agentId) {
            console.error("[AgentTerminal] handleSubmit blocked: no agentId available");
            setError("Agent not ready. Please try again.");
            submitInFlightRef.current = false;
            return;
        }
        clearStopGuard();
        clearStaleRunningLoadSuppression(agentStub.id);
        const hadQuestionnaireDialogOpen = activeInlineDialogRef.current?.request.dialogType === "questionnaire";
        const suppressedQueuedPromptToken = hadQuestionnaireDialogOpen && savedPrompt
            ? registerSuppressedQueuedPrompt(agentId, savedPrompt)
            : null;
        cancelActiveInlineDialog();
        const tempMessageId = createTempAgentMessageId();
        try {
            setIsSubmitting(true);
            setError(null);
            setPrompt("");
            if (savedPrompt || stagedAttachments.length > 0) {
                const optimisticUserMessage = createOptimisticUserMessage({
                    id: tempMessageId,
                    agentId,
                    content: savedPrompt,
                    attachments: stagedAttachments,
                });
                addOptimisticTranscriptMessage(optimisticUserMessage);
                console.log("[AgentTerminal] Added optimistic user message:", tempMessageId);
            }
            setShouldAutoScroll(true);
            const requestSettings = getPendingRequestSettings();
            const effectiveContext = await buildSubmitContext({
                profileName: requestSettings.profileName,
                liveContextWarning: "[AgentTerminal] Failed to compute live context:",
            });
            const request = createAgentStartRequest({
                agentId,
                message: savedPrompt,
                sessionId: editContext.sessionId,
                requestSettings,
                context: effectiveContext,
                clientMessageId: tempMessageId,
                attachments: stagedAttachments,
            });
            console.log("[AgentTerminal] Calling startAgentSessionRun for agent:", agentId);
            lastNonHeartbeatUpdateAtRef.current = Date.now();
            const response = await startAgentSessionRun(request);
            console.log("[AgentTerminal] startAgentSessionRun response:", response);
            // The submit was accepted by the backend; a real prompt supersedes any pending hint.
            clearSuggestion?.();
            handleSubmitResponse({
                response,
                tempMessageId,
                suppressedQueuedPromptToken,
            });
            clearStagedAttachments?.();
            await persistPendingSettingsIfNeeded();
            setPromptHistory((prev) => [
                savedPrompt,
                ...prev.filter((p) => p !== savedPrompt).slice(0, 9),
            ]);
            setCurrentHistoryIndex(-1);
            await onInteractionSubmitted?.();
        }
        catch (err) {
            console.error("[AgentTerminal] Failed to submit prompt:", err);
            clearSuppressedQueuedPrompt(suppressedQueuedPromptToken);
            setError(getSubmitErrorMessage(err));
            setIsWaitingForResponse(false);
            isWaitingRef.current = false;
            removeOptimisticTranscriptMessage(tempMessageId);
            setPrompt(savedPrompt);
        }
        finally {
            setIsSubmitting(false);
            submitInFlightRef.current = false;
        }
    }, [
        activeInlineDialogRef,
        activePlaceholderInput,
        addOptimisticTranscriptMessage,
        agent?.id,
        agent?.status,
        agentStub.id,
        agentStub.status,
        allPlaceholdersFilled,
        buildSubmitContext,
        cancelActiveInlineDialog,
        clearStopGuard,
        clearStagedAttachments,
        clearSuggestion,
        clearSuppressedQueuedPrompt,
        editContext,
        getStagedAttachments,
        getPendingRequestSettings,
        handleSubmitResponse,
        isStopGuardActive,
        isSubmitting,
        isWaitingRef,
        lastNonHeartbeatUpdateAtRef,
        onInteractionSubmitted,
        persistPendingSettingsIfNeeded,
        placeholderInputRef,
        prompt,
        promptPlaceholderInputRef,
        readOnly,
        registerSuppressedQueuedPrompt,
        removeOptimisticTranscriptMessage,
        setCurrentHistoryIndex,
        setError,
        setIsAgentThinking,
        setIsSubmitting,
        setIsWaitingForResponse,
        setPrompt,
        setPromptHistory,
        setShouldAutoScroll,
        shouldSubmitFilledPlaceholderInputRef,
        submitInFlightRef,
        supersedePendingApprovals,
    ]);
    const handlePushQueuedPrompt = useCallback(async (queuedPrompt) => {
        if (readOnly) {
            console.warn("[AgentTerminal] handlePushQueuedPrompt blocked: read-only access");
            return;
        }
        if (isStopGuardActive) {
            console.warn("[AgentTerminal] handlePushQueuedPrompt blocked: agent is stopping");
            setError("The agent is stopping. Wait a moment before steering it.");
            return;
        }
        if (isSubmitting || submitInFlightRef.current) {
            console.warn("[AgentTerminal] handlePushQueuedPrompt blocked: already submitting");
            return;
        }
        const savedPrompt = queuedPrompt.prompt.trim();
        if (!queuedPrompt.id || !savedPrompt) {
            console.warn("[AgentTerminal] handlePushQueuedPrompt blocked: invalid queued prompt");
            return;
        }
        submitInFlightRef.current = true;
        if (!(await supersedePendingApprovals())) {
            submitInFlightRef.current = false;
            return;
        }
        if (!editContext) {
            console.error("[AgentTerminal] handlePushQueuedPrompt blocked: editContext is undefined");
            setError("Editor context not available. Please refresh the page.");
            submitInFlightRef.current = false;
            return;
        }
        const agentId = agent?.id || agentStub.id;
        if (!agentId) {
            console.error("[AgentTerminal] handlePushQueuedPrompt blocked: no agentId available");
            setError("Agent not ready. Please try again.");
            submitInFlightRef.current = false;
            return;
        }
        clearStopGuard();
        clearStaleRunningLoadSuppression(agentStub.id);
        cancelActiveInlineDialog();
        const tempMessageId = createTempAgentMessageId();
        try {
            setIsSubmitting(true);
            setError(null);
            setPrompt("");
            const optimisticUserMessage = createOptimisticUserMessage({
                id: tempMessageId,
                agentId,
                content: savedPrompt,
            });
            addOptimisticTranscriptMessage(optimisticUserMessage);
            setShouldAutoScroll(true);
            setIsWaitingForResponse(true);
            isWaitingRef.current = true;
            setIsAgentThinking(true);
            const requestSettings = getPendingRequestSettings();
            const effectiveContext = await buildSubmitContext({
                profileName: requestSettings.profileName,
                liveContextWarning: "[AgentTerminal] Failed to compute live context for queued prompt push:",
            });
            const request = createAgentStartRequest({
                agentId,
                message: savedPrompt,
                sessionId: editContext.sessionId,
                requestSettings,
                context: effectiveContext,
                clientMessageId: tempMessageId,
            });
            lastNonHeartbeatUpdateAtRef.current = Date.now();
            const response = await pushQueuedPromptSessionRun({
                ...request,
                queuedPromptId: queuedPrompt.id,
            });
            // The queued prompt was accepted by the backend; supersede any pending hint.
            clearSuggestion?.();
            handleSubmitResponse({
                response,
                tempMessageId,
                suppressedQueuedPromptToken: null,
            });
            await persistPendingSettingsIfNeeded();
            setPromptHistory((prev) => [
                savedPrompt,
                ...prev.filter((p) => p !== savedPrompt).slice(0, 9),
            ]);
            setCurrentHistoryIndex(-1);
            await onInteractionSubmitted?.();
        }
        catch (err) {
            console.error("[AgentTerminal] Failed to push queued prompt:", err);
            setError(getSubmitErrorMessage(err));
            setIsWaitingForResponse(false);
            isWaitingRef.current = false;
            setIsAgentThinking(false);
            removeOptimisticTranscriptMessage(tempMessageId);
        }
        finally {
            setIsSubmitting(false);
            submitInFlightRef.current = false;
        }
    }, [
        addOptimisticTranscriptMessage,
        agent?.id,
        agentStub.id,
        buildSubmitContext,
        cancelActiveInlineDialog,
        clearStopGuard,
        clearSuggestion,
        editContext,
        getPendingRequestSettings,
        handleSubmitResponse,
        isStopGuardActive,
        isSubmitting,
        isWaitingRef,
        lastNonHeartbeatUpdateAtRef,
        onInteractionSubmitted,
        persistPendingSettingsIfNeeded,
        readOnly,
        removeOptimisticTranscriptMessage,
        setCurrentHistoryIndex,
        setError,
        setIsAgentThinking,
        setIsSubmitting,
        setIsWaitingForResponse,
        setPrompt,
        setPromptHistory,
        setShouldAutoScroll,
        supersedePendingApprovals,
    ]);
    const sendQuickMessage = useCallback(async (text) => {
        if (readOnly) {
            console.warn("[AgentTerminal] sendQuickMessage blocked: read-only access");
            return;
        }
        if (isStopGuardActive) {
            console.warn("[AgentTerminal] sendQuickMessage blocked: agent is stopping");
            setError("The agent is stopping. Wait a moment before sending again.");
            return;
        }
        const savedPrompt = text.trim();
        if (!savedPrompt) {
            console.warn("[AgentTerminal] sendQuickMessage blocked: empty text");
            return;
        }
        if (isSubmitting) {
            console.warn("[AgentTerminal] sendQuickMessage blocked: already submitting");
            return;
        }
        if (hasPendingApprovals()) {
            console.warn("[AgentTerminal] sendQuickMessage blocked: pending tool call approval");
            return;
        }
        if (!editContext) {
            console.error("[AgentTerminal] sendQuickMessage blocked: editContext is undefined");
            setError("Editor context not available. Please refresh the page.");
            return;
        }
        const agentId = agent?.id;
        if (!agentId) {
            console.error("[AgentTerminal] sendQuickMessage blocked: no agentId available");
            setError("Agent not ready. Please try again.");
            return;
        }
        const tempMessageId = createTempAgentMessageId();
        try {
            setIsSubmitting(true);
            setError(null);
            const optimisticUserMessage = createOptimisticUserMessage({
                id: tempMessageId,
                agentId,
                content: savedPrompt,
            });
            addOptimisticTranscriptMessage(optimisticUserMessage);
            console.log("[AgentTerminal] Added optimistic quick message:", tempMessageId);
            setIsWaitingForResponse(true);
            isWaitingRef.current = true;
            setIsAgentThinking(true);
            setShouldAutoScroll(true);
            const requestSettings = getPendingRequestSettings();
            const effectiveContext = await buildSubmitContext({
                profileName: requestSettings.profileName,
                liveContextWarning: "[AgentTerminal] Failed to compute live context for quick message:",
            });
            const request = createAgentStartRequest({
                agentId,
                message: savedPrompt,
                sessionId: editContext.sessionId,
                requestSettings,
                context: effectiveContext,
                clientMessageId: tempMessageId,
            });
            console.log("[AgentTerminal] Calling startAgentSessionRun for quick message");
            await startAgentSessionRun(request);
            await persistPendingSettingsIfNeeded();
            await onInteractionSubmitted?.();
        }
        catch (err) {
            console.error("[AgentTerminal] Failed to submit quick message:", err);
            setError(getSubmitErrorMessage(err));
            setIsWaitingForResponse(false);
            isWaitingRef.current = false;
            removeOptimisticTranscriptMessage(tempMessageId);
        }
        finally {
            setIsSubmitting(false);
        }
    }, [
        addOptimisticTranscriptMessage,
        agent?.id,
        buildSubmitContext,
        editContext,
        getPendingRequestSettings,
        hasPendingApprovals,
        isStopGuardActive,
        isSubmitting,
        isWaitingRef,
        onInteractionSubmitted,
        persistPendingSettingsIfNeeded,
        readOnly,
        removeOptimisticTranscriptMessage,
        setError,
        setIsAgentThinking,
        setIsSubmitting,
        setIsWaitingForResponse,
        setShouldAutoScroll,
    ]);
    return { handleSubmit, handlePushQueuedPrompt, sendQuickMessage };
}
//# sourceMappingURL=useAgentSubmitHandlers.js.map