"use client";
import { useCallback, useRef, useState } from "react";
import { create } from "@bufbuild/protobuf";
import { CancelAgentExecutionInputSchema, TerminateAgentExecutionInputSchema, PauseAgentExecutionInputSchema, ResumeAgentExecutionInputSchema, } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/io_pb";
import { useStigmer } from "../hooks.js";
import { toError } from "../internal/toError.js";
/**
 * Behavior hook that encapsulates agent execution lifecycle actions.
 *
 * The agent-execution analog of {@link useWorkflowExecutionActions}: each
 * action calls the corresponding RPC and returns the updated execution, or
 * `null` on failure (with `error` populated).
 *
 * Pass `null` for `executionId` to disable all actions (they become no-ops
 * that return `null`).
 *
 * Headless by design — embedders can wire a custom Stop/Cancel control
 * directly to this hook. The session chat uses it via
 * {@link useSessionConversation}'s `stop` / `isStoppable`.
 *
 * @example
 * ```tsx
 * const actions = useAgentExecutionActions(executionId, {
 *   onSuccess: () => refetch(),
 * });
 *
 * // A single Stop button that escalates on repeat press.
 * <button onClick={() => actions.stop()} disabled={actions.isSubmitting}>
 *   Stop
 * </button>
 * ```
 */
export function useAgentExecutionActions(executionId, options) {
    const stigmer = useStigmer();
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [error, setError] = useState(null);
    const executionIdRef = useRef(executionId);
    executionIdRef.current = executionId;
    const stigmerRef = useRef(stigmer);
    stigmerRef.current = stigmer;
    const onSuccessRef = useRef(options?.onSuccess);
    onSuccessRef.current = options?.onSuccess;
    const clearError = useCallback(() => setError(null), []);
    const wrap = useCallback(async (fn) => {
        if (!executionIdRef.current)
            return null;
        setIsSubmitting(true);
        setError(null);
        try {
            const result = await fn();
            onSuccessRef.current?.(result);
            return result;
        }
        catch (err) {
            setError(toError(err));
            return null;
        }
        finally {
            setIsSubmitting(false);
        }
    }, []);
    const cancel = useCallback((reason) => wrap(() => stigmerRef.current.agentExecution.cancel(create(CancelAgentExecutionInputSchema, {
        id: executionIdRef.current,
        reason: reason ?? "",
    }))), [wrap]);
    const terminate = useCallback((reason) => wrap(() => stigmerRef.current.agentExecution.terminate(create(TerminateAgentExecutionInputSchema, {
        id: executionIdRef.current,
        reason: reason ?? "",
    }))), [wrap]);
    const pause = useCallback((reason) => wrap(() => stigmerRef.current.agentExecution.pause(create(PauseAgentExecutionInputSchema, {
        id: executionIdRef.current,
        reason: reason ?? "",
    }))), [wrap]);
    const resume = useCallback(() => wrap(() => stigmerRef.current.agentExecution.resume(create(ResumeAgentExecutionInputSchema, {
        id: executionIdRef.current,
    }))), [wrap]);
    // Escalation state: remembers whether a graceful cancel has already been
    // issued for the current execution id. Keyed by id so a new execution
    // always begins with cancel rather than inheriting a stale "escalate" flag.
    const stopStateRef = useRef(null);
    const stop = useCallback((reason) => {
        const id = executionIdRef.current;
        if (!id)
            return Promise.resolve(null);
        if (stopStateRef.current?.id !== id) {
            stopStateRef.current = { id, cancelIssued: false };
        }
        if (!stopStateRef.current.cancelIssued) {
            stopStateRef.current.cancelIssued = true;
            return cancel(reason);
        }
        return terminate(reason);
    }, [cancel, terminate]);
    return {
        cancel,
        terminate,
        pause,
        resume,
        stop,
        isSubmitting,
        error,
        clearError,
    };
}
//# sourceMappingURL=useAgentExecutionActions.js.map