import { useCallback, useEffect, useRef, } from "react";
import { updateAgentSessionContext } from "./useAgentSessionSync";
export function useAgentEditorContextSync(input) {
    const { agent, agentMetadata, activeProfile, profiles, editContext, fieldsContext, buildCurrentContext, sanitizeAgentMetadata, setAgentMetadata, } = input;
    const previousContextRef = useRef("");
    useEffect(() => {
        const normalizedAgentProfileId = agent?.profileId?.toLowerCase();
        const profile = activeProfile ||
            profiles.find((p) => p.id?.toLowerCase() === normalizedAgentProfileId);
        if (!profile)
            return;
        const isLiveMode = profile.editorContextMode === "live";
        if (!isLiveMode) {
            return;
        }
        const currentItemKey = editContext?.currentItemDescriptor
            ? `${editContext.currentItemDescriptor.id}-${editContext.currentItemDescriptor.language}-${editContext.currentItemDescriptor.version}`
            : "";
        const selectionKey = editContext?.selection?.join(",") || "";
        const focusedFieldKey = fieldsContext?.focusedField?.fieldId || "";
        const contextKey = `${currentItemKey}|${selectionKey}|${focusedFieldKey}`;
        if (contextKey === previousContextRef.current) {
            return;
        }
        previousContextRef.current = contextKey;
        void (async () => {
            try {
                const currentCtx = buildCurrentContext();
                if (!currentCtx) {
                    return;
                }
                const existingMeta = agentMetadata || {};
                const merged = {
                    ...existingMeta,
                    items: currentCtx.items ? [...currentCtx.items] : undefined,
                    currentItemId: currentCtx.currentItemId,
                    components: currentCtx.components
                        ? [...currentCtx.components]
                        : undefined,
                    field: currentCtx.field ? { ...currentCtx.field } : undefined,
                };
                if (!merged.items || merged.items.length === 0) {
                    delete merged.items;
                }
                if (!merged.components || merged.components.length === 0) {
                    delete merged.components;
                }
                if (!merged.field) {
                    delete merged.field;
                }
                const sanitized = sanitizeAgentMetadata(merged);
                setAgentMetadata(sanitized ? { ...sanitized } : null);
                if (agent?.id && agent.status !== "new") {
                    if (typeof requestIdleCallback !== "undefined") {
                        requestIdleCallback(async () => {
                            await updateAgentSessionContext(agent.id, merged);
                        }, { timeout: 1000 });
                    }
                    else {
                        setTimeout(async () => {
                            await updateAgentSessionContext(agent.id, merged);
                        }, 0);
                    }
                }
            }
            catch (err) {
                console.error("[Live Context] Failed to update context:", err);
            }
        })();
    }, [
        agent?.id,
        agent?.status,
        agent?.profileId,
        activeProfile?.editorContextMode,
        profiles,
        editContext?.currentItemDescriptor?.id,
        editContext?.currentItemDescriptor?.language,
        editContext?.currentItemDescriptor?.version,
        editContext?.selection,
        fieldsContext?.focusedField?.fieldId,
        buildCurrentContext,
        agentMetadata,
        sanitizeAgentMetadata,
        setAgentMetadata,
    ]);
    const handleRefreshContext = useCallback(async () => {
        if (!agent?.id)
            return;
        const normalizedAgentProfileId = agent?.profileId?.toLowerCase();
        const refreshProfile = activeProfile ||
            profiles.find((p) => p.id?.toLowerCase() === normalizedAgentProfileId);
        if (refreshProfile?.editorContextMode === "none") {
            editContext?.showInfoToast({
                summary: "This profile excludes editor context.",
            });
            return;
        }
        try {
            const currentCtx = buildCurrentContext();
            if (!currentCtx) {
                return;
            }
            const existingMeta = agentMetadata || {};
            const merged = {
                ...existingMeta,
                items: currentCtx.items ? [...currentCtx.items] : undefined,
                currentItemId: currentCtx.currentItemId,
                components: currentCtx.components
                    ? [...currentCtx.components]
                    : undefined,
                field: currentCtx.field ? { ...currentCtx.field } : undefined,
                activeWorkspace: currentCtx.activeWorkspace,
                hasPageLoaded: currentCtx.hasPageLoaded,
            };
            const sanitized = sanitizeAgentMetadata(merged);
            setAgentMetadata(sanitized ? { ...sanitized } : null);
            if (agent.status !== "new") {
                await updateAgentSessionContext(agent.id, merged);
            }
            editContext?.showInfoToast({
                summary: "Context updated to current page/selection",
            });
        }
        catch (err) {
            console.error("[Refresh Context] Failed:", err);
            editContext?.showErrorToast(err);
        }
    }, [
        agent?.id,
        agent?.status,
        agent?.profileId,
        agentMetadata,
        buildCurrentContext,
        sanitizeAgentMetadata,
        setAgentMetadata,
        editContext,
        activeProfile,
        profiles,
    ]);
    return { handleRefreshContext };
}
//# sourceMappingURL=useAgentEditorContextSync.js.map