"use client";
import { useCallback, useState } from "react";
import { PENDING_SUBJECT, } from "@stigmer/sdk";
import { useStigmer } from "../hooks";
import { toError } from "../internal/toError";
import { toProtoHarness } from "../models/harness";
import { toProtoExecutionTarget } from "./execution-target";
import { useExecutionTarget } from "../execution-target-context";
/**
 * Behavior hook that wraps `session.create()` with loading/error state.
 *
 * Creates a Session — the conversation context that holds workspace
 * entries, thread state, and sandbox references.
 *
 * Exactly one agent resolution strategy must be provided:
 *
 * 1. **`agentInstanceId`** — Use a pre-provisioned instance directly.
 *    Typical for platform builders who manage instances programmatically.
 * 2. **`agentRef`** — Resolve the agent's default instance via
 *    `agent.getByReference()`. Useful when you know the agent slug
 *    but not the instance ID.
 *
 * This hook maps 1:1 to the Session aggregate. To start the first
 * execution within the session, compose with {@link useCreateAgentExecution}.
 *
 * @example
 * ```tsx
 * // Platform builder: pre-provisioned instance
 * const { create } = useCreateSession();
 * await create({ org: "acme", agentInstanceId: "inst-abc123" });
 * ```
 *
 * @example
 * ```tsx
 * // Agent reference: resolves to the agent's default instance
 * const { create } = useCreateSession();
 * await create({
 *   org: "acme",
 *   agentRef: { org: "acme", slug: "code-reviewer" },
 * });
 * ```
 */
export function useCreateSession() {
    const stigmer = useStigmer();
    const contextTarget = useExecutionTarget();
    const [isCreating, setIsCreating] = useState(false);
    const [error, setError] = useState(null);
    const clearError = useCallback(() => setError(null), []);
    const create = useCallback(async (input) => {
        setIsCreating(true);
        setError(null);
        try {
            let resolvedInstanceId;
            if (input.agentInstanceId) {
                resolvedInstanceId = input.agentInstanceId;
            }
            else if (input.agentRef) {
                const agent = await stigmer.agent.getByReference(input.agentRef);
                const defaultId = agent.status?.defaultInstanceId;
                if (!defaultId) {
                    throw new Error(`Agent "${input.agentRef.org}/${input.agentRef.slug}" does not have a default instance. ` +
                        `Pass an explicit agentInstanceId instead.`);
                }
                resolvedInstanceId = defaultId;
            }
            else {
                throw new Error("useCreateSession requires either agentInstanceId or agentRef. " +
                    "Provide one to specify which agent this session should use.");
            }
            const resolvedTarget = input.executionTarget ?? contextTarget;
            const session = await stigmer.session.create({
                name: `session-${Date.now()}`,
                org: input.org,
                subject: input.subject ?? PENDING_SUBJECT,
                workspaceEntries: input.workspaceEntries,
                mcpServerUsages: input.mcpServerUsages,
                skillRefs: input.skillRefs,
                agentInstanceId: resolvedInstanceId,
                harness: input.harness ? toProtoHarness(input.harness) : undefined,
                executionTarget: resolvedTarget
                    ? toProtoExecutionTarget(resolvedTarget)
                    : undefined,
            });
            const sessionId = session.metadata.id;
            // Worker lifecycle is owned by the session view (useSessionConversation
            // attaches on open / detaches on close). The new-session flow attaches
            // eagerly for the first execution; creation alone needs no worker.
            return { sessionId };
        }
        catch (err) {
            setError(toError(err));
            throw err;
        }
        finally {
            setIsCreating(false);
        }
    }, [stigmer, contextTarget]);
    return { create, isCreating, error, clearError };
}
//# sourceMappingURL=useCreateSession.js.map