"use client";
import { useCallback, useState } from "react";
import { create } from "@bufbuild/protobuf";
import { ConnectInputSchema } from "@stigmer/protos/ai/stigmer/agentic/mcpserver/v1/io_pb";
import { useStigmer } from "../hooks";
import { resolveDeclaredSystemEnvVars } from "../environment/systemEnvVars";
import { toError } from "../internal/toError";
/**
 * Action hook for connecting to an MCP server.
 *
 * Triggers server-side capability discovery and tool approval
 * classification in a single operation. The backend enumerates the
 * server's tools and resource templates, then classifies each tool's
 * approval policy via a structured-output LLM call.
 *
 * Platform system env vars (`STIGMER_SERVER_ADDRESS`,
 * `STIGMER_API_KEY`) are injected only when the target MCP server
 * declares them in `spec.env`. Pass the server's declared env keys
 * via `declaredEnvKeys` so the hook knows which system vars to
 * include. When not provided, no system vars are injected.
 *
 * Additional one-time credentials can be passed via `runtimeEnv`
 * and will override both system vars and personal env values.
 *
 * @example
 * ```tsx
 * const { connect, isConnecting, error } = useMcpServerConnect();
 * const { refetch } = useMcpServer(org, slug);
 *
 * // Saved credentials: already in personal environment
 * async function handleConnectSaved() {
 *   const envKeys = Object.keys(mcpServer.spec?.env ?? {});
 *   await connect(mcpServer.metadata.id, undefined, envKeys);
 *   refetch();
 * }
 *
 * // One-time use: pass credentials directly
 * async function handleConnectTemporary(values: Record<string, EnvVarInput>) {
 *   const envKeys = Object.keys(mcpServer.spec?.env ?? {});
 *   await connect(mcpServer.metadata.id, values, envKeys);
 *   refetch();
 * }
 * ```
 */
export function useMcpServerConnect() {
    const stigmer = useStigmer();
    const [isConnecting, setIsConnecting] = useState(false);
    const [error, setError] = useState(null);
    const clearError = useCallback(() => setError(null), []);
    const connect = useCallback(async (mcpServerId, org, runtimeEnv, declaredEnvKeys) => {
        setIsConnecting(true);
        setError(null);
        try {
            const systemEnv = declaredEnvKeys
                ? await resolveDeclaredSystemEnvVars(stigmer, declaredEnvKeys)
                : {};
            const mergedEnv = { ...systemEnv, ...(runtimeEnv ?? {}) };
            const runtimeEnvMap = {};
            for (const [key, envInput] of Object.entries(mergedEnv)) {
                runtimeEnvMap[key] = {
                    value: envInput.value,
                    isSecret: envInput.isSecret ?? false,
                };
            }
            const input = create(ConnectInputSchema, {
                mcpServerId,
                org,
                ...(Object.keys(runtimeEnvMap).length > 0
                    ? { runtimeEnv: runtimeEnvMap }
                    : {}),
            });
            return await stigmer.mcpServer.connect(input);
        }
        catch (err) {
            const wrapped = toError(err);
            setError(wrapped);
            throw wrapped;
        }
        finally {
            setIsConnecting(false);
        }
    }, [stigmer]);
    return { connect, isConnecting, error, clearError };
}
//# sourceMappingURL=useMcpServerConnect.js.map