/*
 * Copyright (c) 2023-2025 Datalayer, Inc.
 * Distributed under the terms of the Modified BSD License.
 */
import { create } from 'zustand';
/**
 * Zustand store for per-project runtime state (kernel connections, agents).
 *
 * Not persisted — the data is ephemeral and only valid while the project
 * component is mounted and a kernel/agent is active.
 *
 * Usage:
 * ```ts
 * import { useProjectStore } from '@datalayer/core/lib/hooks';
 *
 * // In Project.tsx — store session when Notebook connects:
 * const setSessionConnection = useProjectStore(s => s.setSessionConnection);
 * <Notebook onSessionConnection={sc => setSessionConnection(projectId, sc)} />
 *
 * // Anywhere — read the kernel for a project:
 * const kernel = useProjectStore(s => s.getKernel(projectId));
 * ```
 */
export const useProjectStore = create()((set, get) => ({
    projects: {},
    currentProjectId: undefined,
    setCurrentProjectId: projectId => set({ currentProjectId: projectId }),
    setSessionConnection: (projectId, sessionConnection) => set(state => ({
        projects: {
            ...state.projects,
            [projectId]: {
                ...state.projects[projectId],
                sessionConnection,
            },
        },
    })),
    setAgent: (projectId, agentPodName, agentName, agentStatus, agentSpecId) => set(state => ({
        projects: {
            ...state.projects,
            [projectId]: {
                ...state.projects[projectId],
                agentPodName,
                agentName,
                // When removing the agent, also clear the status.
                // When setting, use provided status or preserve existing.
                agentStatus: agentPodName !== undefined
                    ? (agentStatus ?? state.projects[projectId]?.agentStatus)
                    : undefined,
                agentSpecId: agentPodName !== undefined
                    ? (agentSpecId ?? state.projects[projectId]?.agentSpecId)
                    : undefined,
            },
        },
    })),
    clearProject: projectId => set(state => {
        const { [projectId]: _, ...rest } = state.projects;
        return { projects: rest };
    }),
    getKernel: projectId => {
        const entry = get().projects[projectId];
        return entry?.sessionConnection?.kernel;
    },
    getEntry: projectId => get().projects[projectId],
}));
