import { useEffect, useMemo, useState } from "react";
import { invalidateAiProfilesCache } from "../../services/aiService";
import { normalizeProfileAllowanceOperations } from "../agentMessageHelpers";
import { loadAgentSessionAvailableTools, loadAgentSessionOperationAllowances, loadAgentSessionSkillCatalog, loadAgentSessionTriggerSubscriptions, refreshAgentAssignedSkillIds, } from "./useAgentSessionSync";
export function useAgentSettingsData(input) {
    const { agent, agentMetadata, activeProfile, isLocalOnlyDraftAgent, mode, showAgentSettings, onReloadProfiles, onAssignedSkillIdsChange, } = input;
    const [availableSkills, setAvailableSkills] = useState([]);
    const [skillRootIds, setSkillRootIds] = useState([]);
    const [selectableTemplateIds, setSelectableTemplateIds] = useState([]);
    const [skillsLoading, setSkillsLoading] = useState(false);
    const [skillsError, setSkillsError] = useState(null);
    const [skillActionError, setSkillActionError] = useState(null);
    const [triggerSubscriptions, setTriggerSubscriptions] = useState([]);
    const [availableTools, setAvailableTools] = useState([]);
    const [operationAllowances, setOperationAllowances] = useState({
        sitecore: [],
        filesystem: [],
    });
    const [triggerSubscriptionsLoading, setTriggerSubscriptionsLoading] = useState(false);
    const [availableToolsLoading, setAvailableToolsLoading] = useState(false);
    const [operationAllowancesLoading, setOperationAllowancesLoading] = useState(false);
    const [triggerSubscriptionsError, setTriggerSubscriptionsError] = useState(null);
    const [availableToolsError, setAvailableToolsError] = useState(null);
    const [operationAllowancesError, setOperationAllowancesError] = useState(null);
    useEffect(() => {
        let active = true;
        const loadSkills = async () => {
            try {
                setSkillsLoading(true);
                setSkillsError(null);
                const catalog = await loadAgentSessionSkillCatalog(false);
                if (active) {
                    setAvailableSkills(catalog.skills.filter((skill) => !skill.disabled));
                    setSkillRootIds(catalog.rootIds);
                    setSelectableTemplateIds(catalog.selectableTemplateIds);
                }
            }
            catch (error) {
                if (active) {
                    setSkillsError(error?.message || "Failed to load skills");
                    setAvailableSkills([]);
                    setSkillRootIds([]);
                    setSelectableTemplateIds([]);
                }
            }
            finally {
                if (active) {
                    setSkillsLoading(false);
                }
            }
        };
        void loadSkills();
        return () => {
            active = false;
        };
    }, []);
    const metadataSelectedSkillIds = useMemo(() => {
        const rawSkillIds = agentMetadata?.additionalData?.skillIds ?? [];
        if (!Array.isArray(rawSkillIds)) {
            return [];
        }
        return rawSkillIds
            .map((value) => String(value || "").trim())
            .filter((value) => value.length > 0);
    }, [agentMetadata]);
    const backendAssignedSkillIds = useMemo(() => {
        const rawSkillIds = agent?.assignedSkillIds ?? [];
        if (!Array.isArray(rawSkillIds)) {
            return [];
        }
        return rawSkillIds
            .map((value) => String(value || "").trim())
            .filter((value) => value.length > 0);
    }, [agent]);
    const preloadedSkillIds = useMemo(() => {
        const rawSkillIds = activeProfile?.preloadSkills ?? [];
        if (!Array.isArray(rawSkillIds)) {
            return [];
        }
        return rawSkillIds
            .map((skill) => String(skill?.id || "").trim())
            .filter((id) => id.length > 0);
    }, [activeProfile?.preloadSkills]);
    const autoAssignedSkillIds = useMemo(() => {
        const preloadedIdSet = new Set(preloadedSkillIds.map((id) => id.toLowerCase()));
        const all = isLocalOnlyDraftAgent
            ? preloadedSkillIds
            : backendAssignedSkillIds.filter((id) => preloadedIdSet.has(id.toLowerCase()));
        const seen = new Set();
        const unique = [];
        for (const id of all) {
            const key = id.toLowerCase();
            if (seen.has(key))
                continue;
            seen.add(key);
            unique.push(id);
        }
        return unique;
    }, [backendAssignedSkillIds, isLocalOnlyDraftAgent, preloadedSkillIds]);
    const selectedSkillIds = useMemo(() => {
        const all = [
            ...autoAssignedSkillIds,
            ...backendAssignedSkillIds,
            ...metadataSelectedSkillIds,
        ];
        const seen = new Set();
        const unique = [];
        for (const id of all) {
            const key = id.toLowerCase();
            if (seen.has(key))
                continue;
            seen.add(key);
            unique.push(id);
        }
        return unique;
    }, [autoAssignedSkillIds, backendAssignedSkillIds, metadataSelectedSkillIds]);
    useEffect(() => {
        let active = true;
        if (!showAgentSettings) {
            return () => {
                active = false;
            };
        }
        invalidateAiProfilesCache();
        void onReloadProfiles?.();
        if (!agent?.id || isLocalOnlyDraftAgent) {
            setTriggerSubscriptions([]);
            setTriggerSubscriptionsLoading(false);
            setTriggerSubscriptionsError(null);
            setAvailableTools([]);
            setAvailableToolsLoading(false);
            setAvailableToolsError(null);
            setOperationAllowances({ sitecore: [], filesystem: [] });
            setOperationAllowancesLoading(false);
            setOperationAllowancesError(null);
            return () => {
                active = false;
            };
        }
        const loadTriggerSubscriptions = async () => {
            try {
                setTriggerSubscriptionsLoading(true);
                setTriggerSubscriptionsError(null);
                const subscriptions = await loadAgentSessionTriggerSubscriptions(agent.id);
                if (active) {
                    setTriggerSubscriptions(subscriptions);
                }
            }
            catch (error) {
                if (active) {
                    setTriggerSubscriptionsError(error?.message || "Failed to load trigger subscriptions");
                }
            }
            finally {
                if (active) {
                    setTriggerSubscriptionsLoading(false);
                }
            }
        };
        const loadOperationAllowances = async () => {
            try {
                setOperationAllowancesLoading(true);
                setOperationAllowancesError(null);
                const allowances = await loadAgentSessionOperationAllowances(agent.id);
                if (active) {
                    setOperationAllowances(allowances);
                }
            }
            catch (error) {
                if (active) {
                    setOperationAllowancesError(error?.message || "Failed to load allowances");
                }
            }
            finally {
                if (active) {
                    setOperationAllowancesLoading(false);
                }
            }
        };
        const loadAvailableTools = async () => {
            try {
                setAvailableToolsLoading(true);
                setAvailableToolsError(null);
                const tools = await loadAgentSessionAvailableTools(agent.id);
                if (active) {
                    setAvailableTools(tools);
                }
            }
            catch (error) {
                if (active) {
                    setAvailableToolsError(error?.message || "Failed to load available tools");
                }
            }
            finally {
                if (active) {
                    setAvailableToolsLoading(false);
                }
            }
        };
        const refreshAssignedSkills = async () => {
            try {
                const latestSkillIds = await refreshAgentAssignedSkillIds(agent.id);
                if (!active)
                    return;
                if (!Array.isArray(latestSkillIds))
                    return;
                onAssignedSkillIdsChange(latestSkillIds);
            }
            catch (error) {
                console.error("Failed to refresh assigned skills:", error);
            }
        };
        void loadTriggerSubscriptions();
        void loadAvailableTools();
        void loadOperationAllowances();
        void refreshAssignedSkills();
        return () => {
            active = false;
        };
    }, [
        showAgentSettings,
        agent?.id,
        agent?.status,
        agent?.userId,
        agent?.profileId,
        isLocalOnlyDraftAgent,
        mode,
        onAssignedSkillIdsChange,
        onReloadProfiles,
    ]);
    const activeTriggerSubscriptions = useMemo(() => triggerSubscriptions.filter((sub) => sub.isActive), [triggerSubscriptions]);
    const profileOperationAllowances = useMemo(() => {
        const profileSource = activeProfile?.id
            ? `preconfigured:profile:${activeProfile.id}`
            : "preconfigured:profile";
        return {
            sitecore: (activeProfile?.sitecoreAllowances ?? []).flatMap((allowance) => {
                const itemIdentifier = String(allowance?.itemIdentifier || "").trim();
                if (!itemIdentifier)
                    return [];
                return normalizeProfileAllowanceOperations(allowance.operationTypes).map((operationType) => ({
                    itemId: itemIdentifier,
                    itemPath: itemIdentifier,
                    operationType,
                    scopeType: "itemSubtree",
                    source: profileSource,
                    grantedBy: null,
                    grantedAt: null,
                }));
            }),
            filesystem: (activeProfile?.filesystemAllowances ?? []).flatMap((allowance) => {
                const normalizedPath = String(allowance?.path || "").trim();
                if (!normalizedPath)
                    return [];
                return normalizeProfileAllowanceOperations(allowance.operationTypes).map((operationType) => ({
                    normalizedPath,
                    operationType,
                    source: profileSource,
                    grantedBy: null,
                    grantedAt: null,
                }));
            }),
        };
    }, [
        activeProfile?.filesystemAllowances,
        activeProfile?.id,
        activeProfile?.sitecoreAllowances,
    ]);
    const displayedOperationAllowances = isLocalOnlyDraftAgent
        ? profileOperationAllowances
        : operationAllowances;
    const displayedOperationAllowancesLoading = isLocalOnlyDraftAgent
        ? false
        : operationAllowancesLoading;
    const displayedOperationAllowancesError = isLocalOnlyDraftAgent
        ? null
        : operationAllowancesError;
    const allowanceGroups = useMemo(() => [
        {
            key: "sitecore",
            label: "Sitecore",
            rows: displayedOperationAllowances.sitecore,
        },
        {
            key: "filesystem",
            label: "Filesystem",
            rows: displayedOperationAllowances.filesystem,
        },
    ], [displayedOperationAllowances]);
    const hasAnyAllowances = useMemo(() => displayedOperationAllowances.sitecore.length > 0 ||
        displayedOperationAllowances.filesystem.length > 0, [displayedOperationAllowances]);
    const allowancesTotalCount = useMemo(() => displayedOperationAllowances.sitecore.length +
        displayedOperationAllowances.filesystem.length, [displayedOperationAllowances]);
    const listedProfileSkillIdSet = useMemo(() => {
        const ids = [
            ...(activeProfile?.availableSkills ?? []),
            ...(activeProfile?.allowedSkills ?? []),
        ]
            .map((skill) => String(skill?.id || "").toLowerCase())
            .filter((id) => id.length > 0);
        return new Set(ids);
    }, [activeProfile?.availableSkills, activeProfile?.allowedSkills]);
    const profileFilteredSkills = useMemo(() => {
        if (listedProfileSkillIdSet.size === 0) {
            return [];
        }
        return availableSkills.filter((skill) => listedProfileSkillIdSet.has(skill.id.toLowerCase()));
    }, [availableSkills, listedProfileSkillIdSet]);
    const manuallyAssignableSkillIdSet = useMemo(() => new Set((activeProfile?.allowedSkills ?? [])
        .map((skill) => String(skill?.id || "").toLowerCase())
        .filter((id) => id.length > 0)), [activeProfile?.allowedSkills]);
    const selectableTemplateIdSet = useMemo(() => new Set(selectableTemplateIds.map((id) => id.toLowerCase())), [selectableTemplateIds]);
    const selectedSkills = useMemo(() => selectedSkillIds
        .map((id) => availableSkills.find((skill) => skill.id.toLowerCase() === id.toLowerCase()))
        .filter((skill) => !!skill), [availableSkills, selectedSkillIds]);
    const selectedSkillSet = useMemo(() => new Set(selectedSkillIds.map((id) => id.toLowerCase())), [selectedSkillIds]);
    const autoAssignedSkillSet = useMemo(() => new Set(autoAssignedSkillIds.map((id) => id.toLowerCase())), [autoAssignedSkillIds]);
    const previewAvailableTools = useMemo(() => {
        const baseToolNames = mode === "read-only"
            ? (activeProfile?.readOnlyToolNames ?? [])
            : (activeProfile?.allowedToolNames ?? []);
        const toolNames = new Set();
        for (const toolName of baseToolNames) {
            const normalized = String(toolName || "").trim();
            if (normalized) {
                toolNames.add(normalized);
            }
        }
        for (const skill of selectedSkills) {
            for (const toolName of skill.additionalAllowedTools ?? []) {
                const normalized = String(toolName || "").trim();
                if (normalized) {
                    toolNames.add(normalized);
                }
            }
        }
        return Array.from(toolNames).sort((a, b) => a.localeCompare(b));
    }, [
        activeProfile?.allowedToolNames,
        activeProfile?.readOnlyToolNames,
        mode,
        selectedSkills,
    ]);
    const displayedAvailableTools = isLocalOnlyDraftAgent
        ? previewAvailableTools
        : availableTools;
    const displayedAvailableToolsLoading = isLocalOnlyDraftAgent
        ? false
        : availableToolsLoading;
    const displayedAvailableToolsError = isLocalOnlyDraftAgent
        ? null
        : availableToolsError;
    return {
        activeTriggerSubscriptions,
        allowanceGroups,
        allowancesTotalCount,
        autoAssignedSkillSet,
        displayedAvailableTools,
        displayedAvailableToolsError,
        displayedAvailableToolsLoading,
        displayedOperationAllowancesError,
        displayedOperationAllowancesLoading,
        hasAnyAllowances,
        manuallyAssignableSkillIdSet,
        metadataSelectedSkillIds,
        profileFilteredSkills,
        selectedSkillIds,
        selectedSkillSet,
        selectedSkills,
        selectableTemplateIdSet,
        setSkillActionError,
        skillActionError,
        skillRootIds,
        skillsError,
        skillsLoading,
        triggerSubscriptionsError,
        triggerSubscriptionsLoading,
    };
}
//# sourceMappingURL=useAgentSettingsData.js.map