"use client";
import { useCallback, useState } from "react";
import { create } from "@bufbuild/protobuf";
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { CreateLaunchTokenRequestSchema } from "@stigmer/protos/ai/stigmer/agentic/runner/v1/io_pb";
import { useStigmer } from "../hooks";
import { toError } from "../internal/toError";
const LAUNCH_RUNNER_SCHEME = "stigmer://launch-runner";
function defaultOpenUrl(url) {
    window.location.href = url;
}
/**
 * Behavior hook that initiates a browser-to-desktop runner launch.
 *
 * Orchestrates two steps:
 * 1. Calls `stigmer.runner.createLaunchToken({ org })` to mint a
 *    one-time, 60-second token backed by the caller's credentials.
 * 2. Opens `stigmer://launch-runner?token={token}` so the OS dispatches
 *    to the Stigmer Desktop app (which exchanges the token for a JWT
 *    and starts a local runner via its CLI sidecar).
 *
 * The hook reports success when the URL is opened. It does **not**
 * detect whether the desktop app is installed or whether the runner
 * actually started — those are observable via `useRunnerList`.
 *
 * @example
 * ```tsx
 * function LaunchButton({ org }: { org: string }) {
 *   const { launch, isLaunching, error } = useLaunchLocalRunner();
 *
 *   return (
 *     <button onClick={() => launch({ org })} disabled={isLaunching}>
 *       {isLaunching ? "Launching…" : "Launch Local Runner"}
 *     </button>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Custom URL handler for non-browser environments
 * const { launch } = useLaunchLocalRunner({
 *   openUrl: (url) => nativeBridge.openExternal(url),
 * });
 * ```
 */
export function useLaunchLocalRunner(options) {
    const stigmer = useStigmer();
    const [isLaunching, setIsLaunching] = useState(false);
    const [error, setError] = useState(null);
    const [lastLaunchResult, setLastLaunchResult] = useState(null);
    const openUrl = options?.openUrl ?? defaultOpenUrl;
    const clearError = useCallback(() => {
        setError(null);
        setLastLaunchResult(null);
    }, []);
    const launch = useCallback(async (input) => {
        setIsLaunching(true);
        setError(null);
        setLastLaunchResult(null);
        try {
            const response = await stigmer.runner.createLaunchToken(create(CreateLaunchTokenRequestSchema, { org: input.org }));
            const url = `${LAUNCH_RUNNER_SCHEME}?token=${encodeURIComponent(response.token)}`;
            const expiresAt = response.expiresAt
                ? timestampDate(response.expiresAt)
                : undefined;
            openUrl(url);
            const result = { url, expiresAt };
            setLastLaunchResult(result);
            return result;
        }
        catch (err) {
            setError(toError(err));
            throw err;
        }
        finally {
            setIsLaunching(false);
        }
    }, [stigmer, openUrl]);
    return { launch, isLaunching, lastLaunchResult, error, clearError };
}
//# sourceMappingURL=useLaunchLocalRunner.js.map