import { useCallback } from "react";
import { assignAgentSessionSkill, persistDraftAgentSession, revokeAgentSessionSkill, updateAgentSessionContext, } from "./useAgentSessionSync";
function getSkillActionErrorMessage(error) {
    const message = error instanceof Error && error.message.trim()
        ? error.message.trim()
        : "Failed to update skill";
    if (message.includes("Skill is not available for this agent profile")) {
        return "This skill cannot be added for the current agent profile.";
    }
    return message;
}
export function useAgentSkillActions(input) {
    const { agent, agentMetadata, activeProfile, profiles, isLocalOnlyDraftAgent, editContext, pendingSettingsRef, getPendingRequestSettings, buildCurrentContext, sanitizeAgentMetadata, setAgent, setAgentMetadata, onAgentUpdate, metadataSelectedSkillIds, selectedSkillSet, readOnly, setSkillActionError, } = input;
    const clearLegacySelectedSkillsFromMetadata = useCallback(async () => {
        const legacySkillIds = metadataSelectedSkillIds;
        if (!agent?.id || legacySkillIds.length === 0) {
            return;
        }
        const current = agentMetadata || {};
        const currentAdditionalData = current.additionalData ||
            {};
        const nextAdditionalData = Object.fromEntries(Object.entries(currentAdditionalData).filter(([key]) => key.toLowerCase() !== "skillids"));
        const next = {
            ...current,
        };
        if (Object.keys(nextAdditionalData).length > 0) {
            next.additionalData = nextAdditionalData;
        }
        else {
            delete next.additionalData;
        }
        try {
            await updateAgentSessionContext(agent.id, next);
            setAgentMetadata(next);
            setAgent((prev) => prev ? { ...prev, agentContext: JSON.stringify(next) } : prev);
        }
        catch (e) {
            console.error("Failed to clear legacy selected skills", e);
        }
    }, [
        agent?.id,
        agentMetadata,
        metadataSelectedSkillIds,
        setAgent,
        setAgentMetadata,
    ]);
    const parsePersistedAgentContext = useCallback((contextJson) => {
        try {
            if (!contextJson)
                return null;
            const parsedContext = JSON.parse(contextJson);
            if (!parsedContext || typeof parsedContext !== "object") {
                return null;
            }
            return sanitizeAgentMetadata(parsedContext);
        }
        catch {
            return null;
        }
    }, [sanitizeAgentMetadata]);
    const buildDraftPersistenceContext = useCallback(() => {
        let effectiveContext = agentMetadata;
        try {
            const normalizedAgentProfileId = agent?.profileId?.toLowerCase();
            const profile = activeProfile ||
                profiles.find((p) => p.id?.toLowerCase() === normalizedAgentProfileId);
            const isLiveMode = profile?.editorContextMode === "live";
            if (isLiveMode && typeof buildCurrentContext === "function") {
                const freshContext = buildCurrentContext();
                if (freshContext) {
                    effectiveContext = {
                        ...(agentMetadata || {}),
                        items: freshContext.items,
                        currentItemId: freshContext.currentItemId,
                        components: freshContext.components,
                        field: freshContext.field,
                        activeWorkspace: freshContext.activeWorkspace,
                        hasPageLoaded: freshContext.hasPageLoaded,
                        openSidebars: freshContext.openSidebars,
                    };
                }
            }
        }
        catch (e) {
            console.warn("[AgentTerminal] Failed to compute draft context:", e);
        }
        return sanitizeAgentMetadata(effectiveContext || null);
    }, [
        activeProfile,
        agent?.profileId,
        agentMetadata,
        buildCurrentContext,
        profiles,
        sanitizeAgentMetadata,
    ]);
    const ensureDraftAgentPersisted = useCallback(async () => {
        if (!agent?.id) {
            throw new Error("Agent not ready. Please try again.");
        }
        if (!isLocalOnlyDraftAgent) {
            return agent;
        }
        const requestSettings = getPendingRequestSettings();
        if (!requestSettings.profileId) {
            throw new Error("Select an agent profile before adding a skill.");
        }
        const effectiveContext = buildDraftPersistenceContext();
        const persistedAgent = await persistDraftAgentSession({
            agentId: agent.id,
            sessionId: editContext?.sessionId || undefined,
            profileId: requestSettings.profileId,
            mode: requestSettings.mode,
            model: requestSettings.modelId || undefined,
            name: agent.name,
            context: effectiveContext,
        });
        pendingSettingsRef.current = null;
        const persistedMetadata = parsePersistedAgentContext(persistedAgent.agentContext) ??
            effectiveContext;
        setAgentMetadata(persistedMetadata ? { ...persistedMetadata } : null);
        setAgent((prev) => {
            const next = {
                ...(prev || {}),
                ...persistedAgent,
            };
            if (prev?.messages?.length && !persistedAgent.messages?.length) {
                next.messages = prev.messages;
            }
            return next;
        });
        onAgentUpdate?.(persistedAgent);
        return persistedAgent;
    }, [
        agent,
        buildDraftPersistenceContext,
        editContext?.sessionId,
        getPendingRequestSettings,
        isLocalOnlyDraftAgent,
        onAgentUpdate,
        parsePersistedAgentContext,
        pendingSettingsRef,
        setAgent,
        setAgentMetadata,
    ]);
    const handleAddSkill = useCallback(async (skillId) => {
        if (readOnly)
            return;
        if (selectedSkillSet.has(skillId.toLowerCase()))
            return;
        if (!agent?.id)
            return;
        try {
            setSkillActionError(null);
            const persistedAgent = await ensureDraftAgentPersisted();
            await assignAgentSessionSkill({ agentId: persistedAgent.id, skillId });
            setAgent((prev) => {
                if (!prev)
                    return prev;
                const currentAssigned = Array.isArray(prev.assignedSkillIds)
                    ? prev.assignedSkillIds
                    : [];
                if (currentAssigned.some((existingId) => String(existingId).toLowerCase() === skillId.toLowerCase())) {
                    return prev;
                }
                return {
                    ...prev,
                    assignedSkillIds: [...currentAssigned, skillId],
                };
            });
            await clearLegacySelectedSkillsFromMetadata();
            return true;
        }
        catch (e) {
            setSkillActionError(getSkillActionErrorMessage(e));
            return false;
        }
    }, [
        agent?.id,
        clearLegacySelectedSkillsFromMetadata,
        ensureDraftAgentPersisted,
        readOnly,
        selectedSkillSet,
        setAgent,
        setSkillActionError,
    ]);
    const handleRemoveSkill = useCallback(async (skillId) => {
        if (readOnly)
            return;
        if (!agent?.id)
            return;
        try {
            setSkillActionError(null);
            await revokeAgentSessionSkill({ agentId: agent.id, skillId });
            setAgent((prev) => {
                if (!prev)
                    return prev;
                const currentAssigned = Array.isArray(prev.assignedSkillIds)
                    ? prev.assignedSkillIds
                    : [];
                return {
                    ...prev,
                    assignedSkillIds: currentAssigned.filter((existingId) => String(existingId).toLowerCase() !== skillId.toLowerCase()),
                };
            });
            await clearLegacySelectedSkillsFromMetadata();
        }
        catch (e) {
            setSkillActionError(getSkillActionErrorMessage(e));
        }
    }, [
        agent?.id,
        clearLegacySelectedSkillsFromMetadata,
        readOnly,
        setAgent,
        setSkillActionError,
    ]);
    return {
        handleAddSkill,
        handleRemoveSkill,
    };
}
//# sourceMappingURL=useAgentSkillActions.js.map