import { useCallback, useRef } from "react";
import { updateAgentSessionSettings } from "./useAgentSessionSync";
export function usePendingAgentSettings(input) {
    const { activeProfile, agentId, mode, profiles, selectedModelId } = input;
    const pendingSettingsRef = useRef(null);
    const persistPendingSettingsIfNeeded = useCallback(async () => {
        try {
            if (!agentId)
                return;
            const pending = pendingSettingsRef.current;
            if (!pending)
                return;
            const payload = {};
            if (pending.modelName)
                payload.model = pending.modelName;
            if (pending.mode)
                payload.mode = pending.mode;
            if (pending.profileId)
                payload.profileId = pending.profileId;
            if (pending.profileName != null) {
                payload.profileName = pending.profileName;
            }
            if (Object.keys(payload).length === 0)
                return;
            await updateAgentSessionSettings(agentId, payload);
            pendingSettingsRef.current = null;
        }
        catch (error) {
            console.error("Failed to persist pending settings", error);
        }
    }, [agentId]);
    const getPendingRequestSettings = useCallback(() => {
        const pending = pendingSettingsRef.current;
        const requestProfile = pending?.profileId
            ? profiles.find((profile) => profile.id === pending.profileId) ||
                activeProfile ||
                profiles[0]
            : activeProfile || profiles[0];
        let requestModelId = selectedModelId;
        if (pending?.modelName) {
            const requestModel = (requestProfile?.models || []).find((model) => (model.name || "").trim().toLowerCase() ===
                pending.modelName?.trim().toLowerCase());
            requestModelId = requestModel?.id || requestModelId;
        }
        return {
            mode: (pending?.mode || mode),
            profileId: pending?.profileId || requestProfile?.id || "",
            profileName: pending?.profileName || requestProfile?.name || "",
            modelId: requestModelId,
        };
    }, [activeProfile, mode, profiles, selectedModelId]);
    return {
        pendingSettingsRef,
        persistPendingSettingsIfNeeded,
        getPendingRequestSettings,
    };
}
export function useAgentSettingsCommands(input) {
    const { activeProfile, agent, agentMetadata, isLocalOnlyDraftAgent, pendingSettingsRef, profiles, readOnly, setActiveProfile, setAgent, setAgentMetadata, setMode, setSelectedModelId, } = input;
    const handleModeSettingsChange = useCallback(async (value) => {
        if (readOnly)
            return;
        const nextMode = value || "supervised";
        const current = agentMetadata || {};
        const nextMeta = {
            ...current,
            mode: nextMode,
        };
        try {
            if (!agent?.id || isLocalOnlyDraftAgent) {
                setMode(nextMode);
                setAgentMetadata(nextMeta);
                pendingSettingsRef.current = {
                    ...(pendingSettingsRef.current || {}),
                    mode: nextMode,
                };
                return;
            }
            const result = await updateAgentSessionSettings(agent.id, {
                mode: nextMode,
            });
            if (result.success === false || result.updates?.mode === false) {
                throw new Error("Mode change was not applied");
            }
            setMode(nextMode);
            setAgentMetadata(nextMeta);
            setAgent((prev) => prev
                ? {
                    ...prev,
                    mode: nextMode,
                    metadata: JSON.stringify(nextMeta),
                }
                : prev);
        }
        catch (error) {
            console.error("Failed to persist mode change", error);
        }
    }, [
        agent?.id,
        agentMetadata,
        isLocalOnlyDraftAgent,
        pendingSettingsRef,
        readOnly,
        setAgent,
        setAgentMetadata,
        setMode,
    ]);
    const handleProfileSettingsChange = useCallback(async (profileId) => {
        if (readOnly)
            return;
        const nextProfile = profiles.find((profile) => profile.id === profileId);
        if (!nextProfile)
            return;
        setActiveProfile(nextProfile);
        try {
            if (agent?.id && !isLocalOnlyDraftAgent) {
                await updateAgentSessionSettings(agent.id, {
                    profileId: nextProfile.id,
                    profileName: nextProfile.name,
                });
            }
            else {
                pendingSettingsRef.current = {
                    ...(pendingSettingsRef.current || {}),
                    profileId: nextProfile.id,
                    profileName: nextProfile.name,
                };
                setAgentMetadata((current) => {
                    const next = {
                        ...(current || {}),
                    };
                    next.profile = nextProfile.name;
                    next.additionalData = {
                        ...(next.additionalData || {}),
                        profileId: nextProfile.id,
                        profileName: nextProfile.name,
                    };
                    return next;
                });
            }
            setAgent((prev) => prev
                ? {
                    ...prev,
                    profileId: nextProfile.id,
                    profileName: nextProfile.name,
                    metadata: JSON.stringify({
                        ...(agentMetadata || {}),
                        profile: nextProfile.name,
                        additionalData: {
                            ...(agentMetadata?.additionalData || {}),
                            profileId: nextProfile.id,
                            profileName: nextProfile.name,
                        },
                    }),
                }
                : prev);
        }
        catch (error) {
            console.error("Failed to persist agent profile", error);
        }
    }, [
        agent?.id,
        agentMetadata,
        isLocalOnlyDraftAgent,
        pendingSettingsRef,
        profiles,
        readOnly,
        setActiveProfile,
        setAgent,
        setAgentMetadata,
    ]);
    const handleModelSettingsChange = useCallback(async (modelId) => {
        if (readOnly)
            return;
        setSelectedModelId(modelId);
        const modelName = activeProfile?.models?.find((model) => model.id === modelId)?.name ||
            "";
        setAgent((prev) => (prev ? { ...prev, model: modelName } : prev));
        try {
            if (agent?.id && !isLocalOnlyDraftAgent) {
                await updateAgentSessionSettings(agent.id, {
                    model: modelName,
                });
            }
            else {
                pendingSettingsRef.current = {
                    ...(pendingSettingsRef.current || {}),
                    modelName,
                };
            }
        }
        catch (error) {
            console.error("Failed to persist agent model", error);
        }
    }, [
        activeProfile?.models,
        agent?.id,
        isLocalOnlyDraftAgent,
        pendingSettingsRef,
        readOnly,
        setAgent,
        setSelectedModelId,
    ]);
    return {
        handleModeSettingsChange,
        handleProfileSettingsChange,
        handleModelSettingsChange,
    };
}
//# sourceMappingURL=useAgentSettingsCommands.js.map