"use client";
import { useCallback, useMemo, useRef, useState } from "react";
import { useStigmer } from "../hooks";
import { toError } from "../internal/toError";
import { useAgentInstanceList } from "./useAgentInstanceList";
import { buildPersonalInstanceInput } from "./buildPersonalInstanceInput";
const PERSONAL_LABELS = {
    "stigmer.ai/personal": "true",
};
/**
 * Layer 2 orchestration hook that manages the caller's personal
 * {@link AgentInstance} for a given organization, optionally scoped
 * to a specific agent.
 *
 * Encapsulates the "personal agent instance" convention: unique slug
 * per user, labels (`stigmer.ai/personal`, `stigmer.ai/for-agent`),
 * and the get-or-create lifecycle. Composes {@link useAgentInstanceList}
 * for declarative reading and the SDK client directly for mutations.
 *
 * Pass `null` as `org` to skip all operations (stable no-op).
 * The `agentId` parameter is optional for read-only use (listing all
 * personal instances) but required for {@link getOrCreate}.
 *
 * This is a Layer 2 **Environment Flow** hook. It provides the managed
 * "personal agent instance" experience used by the Stigmer Console.
 * Callers who pre-provision agent instances should use the Layer 1
 * building-block hook {@link useCreateAgentInstance} directly.
 *
 * @example
 * ```tsx
 * // Read-only: check if a personal instance exists for an agent
 * const { agentInstance, isLoading } = usePersonalAgentInstance(
 *   "acme",
 *   agent.metadata.id,
 * );
 *
 * // Get-or-create: ensure a personal instance exists
 * const { getOrCreate, isMutating } = usePersonalAgentInstance(
 *   "acme",
 *   agent.metadata.id,
 * );
 *
 * const instance = await getOrCreate({
 *   agentSlug: "my-github-bot",
 *   personalEnvironmentRef: { org: "acme", slug: "env-personal-a1b2c3d4" },
 * });
 * ```
 */
export function usePersonalAgentInstance(org, agentId) {
    const stigmer = useStigmer();
    const { agentInstances, isLoading, error: listError, refetch } = useAgentInstanceList(org, PERSONAL_LABELS);
    const agentInstance = useMemo(() => {
        if (agentInstances.length === 0)
            return null;
        if (!agentId)
            return agentInstances[0] ?? null;
        return (agentInstances.find((ai) => ai.spec?.agentId === agentId) ?? null);
    }, [agentInstances, agentId]);
    const [isMutating, setIsMutating] = useState(false);
    const [mutationError, setMutationError] = useState(null);
    const agentInstanceRef = useRef(agentInstance);
    agentInstanceRef.current = agentInstance;
    const error = mutationError ?? listError;
    const getOrCreate = useCallback(async (input) => {
        if (agentInstanceRef.current)
            return agentInstanceRef.current;
        if (!org) {
            throw new Error("usePersonalAgentInstance: cannot call getOrCreate when org is null.");
        }
        if (!agentId) {
            throw new Error("usePersonalAgentInstance: agentId is required for getOrCreate. " +
                "Pass the agent's ID as the second argument to the hook.");
        }
        setIsMutating(true);
        setMutationError(null);
        try {
            const created = await stigmer.agentInstance.create(buildPersonalInstanceInput({
                org,
                agentId,
                agentSlug: input.agentSlug,
                environmentRef: input.personalEnvironmentRef,
            }));
            refetch();
            return created;
        }
        catch (err) {
            setMutationError(toError(err));
            throw err;
        }
        finally {
            setIsMutating(false);
        }
    }, [org, agentId, stigmer, refetch]);
    return {
        agentInstance,
        isLoading,
        error,
        refetch,
        getOrCreate,
        isMutating,
    };
}
//# sourceMappingURL=usePersonalAgentInstance.js.map