import { useCallback, useEffect, useMemo, useState } from "react";
import { DIALOG_TYPES } from "../dialogs/agentDialogTypes";
import { cancelAgentSessionDialog, claimAgentSessionBrowser, getAgentSessionBrowserCaptureClaim, releaseAgentSessionBrowser, setAgentSessionBrowserCaptureClaim, } from "./useAgentSessionSync";
export function isBrowserCaptureDialogType(dialogType) {
    return (dialogType === DIALOG_TYPES.CAPTURE_PAGE_DOM ||
        dialogType === DIALOG_TYPES.CAPTURE_PAGE_SCREENSHOT);
}
export function useAgentBrowserCapture(input) {
    const { agentId, agentStatus, sessionId, metadata, terminalInstanceIdRef, setMetadata, sanitizeMetadata, setMutationPending, showErrorToast, } = input;
    const [pendingDialogType, setPendingDialogType] = useState(null);
    const [pendingCallbackId, setPendingCallbackId] = useState(null);
    const browserCaptureClaim = useMemo(() => getAgentSessionBrowserCaptureClaim(metadata), [metadata]);
    const isPendingBrowserCaptureWait = isBrowserCaptureDialogType(pendingDialogType);
    const currentSessionId = sessionId?.trim() || "";
    const claimedSessionId = browserCaptureClaim?.sessionId?.trim() || "";
    const isClaimedByCurrentSession = !!currentSessionId &&
        !!claimedSessionId &&
        currentSessionId.toLowerCase() === claimedSessionId.toLowerCase();
    const isClaimedByAnotherBrowser = !!claimedSessionId && !isClaimedByCurrentSession;
    const clearPendingBrowserCaptureWait = useCallback(() => {
        setPendingDialogType(null);
        setPendingCallbackId(null);
    }, []);
    const setPendingBrowserCaptureWait = useCallback((dialogType, callbackId) => {
        if (!isBrowserCaptureDialogType(dialogType)) {
            clearPendingBrowserCaptureWait();
            return;
        }
        setPendingDialogType(dialogType);
        setPendingCallbackId(callbackId?.trim() || null);
    }, [clearPendingBrowserCaptureWait]);
    useEffect(() => {
        if (agentStatus !== "waitingForInput") {
            clearPendingBrowserCaptureWait();
        }
    }, [agentStatus, clearPendingBrowserCaptureWait]);
    const claimBrowser = useCallback(async (takeOver) => {
        if (!agentId || !sessionId)
            return;
        setMutationPending(true);
        try {
            const response = await claimAgentSessionBrowser({
                agentId,
                sessionId,
                takeOver,
                terminalInstanceId: terminalInstanceIdRef.current,
            });
            setMetadata((prev) => sanitizeMetadata(setAgentSessionBrowserCaptureClaim(prev, response.claim || null)));
        }
        catch (error) {
            console.error("[AgentTerminal] Failed to claim browser:", error);
            showErrorToast?.(error);
        }
        finally {
            setMutationPending(false);
        }
    }, [
        agentId,
        sanitizeMetadata,
        sessionId,
        setMetadata,
        setMutationPending,
        showErrorToast,
        terminalInstanceIdRef,
    ]);
    const releaseBrowser = useCallback(async () => {
        if (!agentId || !sessionId)
            return;
        setMutationPending(true);
        try {
            const response = await releaseAgentSessionBrowser({
                agentId,
                sessionId,
                terminalInstanceId: terminalInstanceIdRef.current,
            });
            setMetadata((prev) => sanitizeMetadata(setAgentSessionBrowserCaptureClaim(prev, response.claim || null)));
        }
        catch (error) {
            console.error("[AgentTerminal] Failed to release browser:", error);
            showErrorToast?.(error);
        }
        finally {
            setMutationPending(false);
        }
    }, [
        agentId,
        sanitizeMetadata,
        sessionId,
        setMetadata,
        setMutationPending,
        showErrorToast,
        terminalInstanceIdRef,
    ]);
    useEffect(() => {
        return () => {
            if (!agentId || !sessionId || !isClaimedByCurrentSession) {
                return;
            }
            void releaseAgentSessionBrowser({
                agentId,
                sessionId,
                terminalInstanceId: terminalInstanceIdRef.current,
            }).catch((error) => {
                console.warn("[AgentTerminal] Failed to release browser on unmount:", error);
            });
        };
    }, [agentId, isClaimedByCurrentSession, sessionId, terminalInstanceIdRef]);
    const cancelBrowserCapture = useCallback(async () => {
        const callbackId = pendingCallbackId;
        if (!callbackId || !sessionId)
            return;
        setMutationPending(true);
        try {
            await cancelAgentSessionDialog({
                callbackId,
                sessionId,
                error: "Cancelled by user from the capture waiting banner.",
            });
            clearPendingBrowserCaptureWait();
        }
        catch (error) {
            console.error("[AgentTerminal] Failed to cancel capture dialog:", error);
            showErrorToast?.(error);
        }
        finally {
            setMutationPending(false);
        }
    }, [
        clearPendingBrowserCaptureWait,
        pendingCallbackId,
        sessionId,
        setMutationPending,
        showErrorToast,
    ]);
    return {
        pendingCallbackId,
        isPendingBrowserCaptureWait,
        isClaimedByCurrentSession,
        isClaimedByAnotherBrowser,
        setPendingBrowserCaptureWait,
        clearPendingBrowserCaptureWait,
        claimBrowser,
        releaseBrowser,
        cancelBrowserCapture,
    };
}
//# sourceMappingURL=useAgentBrowserCapture.js.map