"use client";
import { useCallback, useState } from "react";
import { create } from "@bufbuild/protobuf";
import { PushSkillFromExecutionArtifactRequestSchema } from "@stigmer/protos/ai/stigmer/agentic/skill/v1/io_pb";
import { useStigmer } from "../hooks";
import { toError } from "../internal/toError";
import { parseResourceYaml } from "./parse-resource-yaml";
/**
 * Behavior hook for applying detected Stigmer resources to an organization.
 *
 * Bridges the detection layer ({@link detectStigmerResource},
 * {@link useDetectSkillPackage}) to the apply action — the user clicks
 * "Apply to [org]" and the resource is created or updated.
 *
 * Handles two parallel apply paths:
 *
 * 1. **YAML resources** (Agent, McpServer): `applyYamlResource(content, org)`
 *    parses the YAML, converts snake_case fields to SDK input types, and
 *    calls the appropriate `apply()` method.
 *
 * 2. **Skill packages** (directory artifacts): `pushSkillPackage(params)`
 *    delegates to the server-side `pushFromExecutionArtifact` RPC.
 *
 * Follows the established mutation hook pattern: `isApplying` + `error` +
 * `clearError`. The result is returned from the promise (not stored in
 * hook state) — consistent with {@link useCreateOrganization} and other
 * SDK mutation hooks.
 *
 * @example
 * ```tsx
 * const { applyYamlResource, pushSkillPackage, isApplying, error, clearError } =
 *   useApplyResource();
 * const [result, setResult] = useState<ApplyResourceResult | null>(null);
 *
 * const handleApply = async () => {
 *   clearError();
 *   try {
 *     if (yamlDetection.detected) {
 *       setResult(await applyYamlResource(content!, activeOrg));
 *     } else if (skillDetection.detected) {
 *       setResult(await pushSkillPackage({
 *         org: activeOrg,
 *         executionId,
 *         storageKey: artifact.storageKey,
 *       }));
 *     }
 *   } catch {
 *     // error state is set by the hook
 *   }
 * };
 * ```
 *
 * @see {@link parseResourceYaml} for the pure YAML-to-input conversion
 * @see {@link detectStigmerResource} for YAML resource detection
 * @see {@link useDetectSkillPackage} for skill package detection
 */
export function useApplyResource() {
    const stigmer = useStigmer();
    const [isApplying, setIsApplying] = useState(false);
    const [error, setError] = useState(null);
    const clearError = useCallback(() => setError(null), []);
    const applyYamlResource = useCallback(async (content, org) => {
        setIsApplying(true);
        setError(null);
        try {
            const parsed = parseResourceYaml(content, org);
            switch (parsed.kind) {
                case "Agent": {
                    const agent = await stigmer.agent.apply(parsed.input);
                    return {
                        kind: "Agent",
                        name: agent.metadata?.name ?? parsed.input.name,
                        org: agent.metadata?.org ?? org,
                        slug: agent.metadata?.slug ?? parsed.input.name,
                    };
                }
                case "McpServer": {
                    const mcpServer = await stigmer.mcpServer.apply(parsed.input);
                    return {
                        kind: "McpServer",
                        name: mcpServer.metadata?.name ?? parsed.input.name,
                        org: mcpServer.metadata?.org ?? org,
                        slug: mcpServer.metadata?.slug ?? parsed.input.name,
                    };
                }
            }
        }
        catch (err) {
            setError(toError(err));
            throw err;
        }
        finally {
            setIsApplying(false);
        }
    }, [stigmer]);
    const pushSkillPackage = useCallback(async (params) => {
        setIsApplying(true);
        setError(null);
        try {
            const request = create(PushSkillFromExecutionArtifactRequestSchema, {
                org: params.org,
                executionId: params.executionId,
                storageKey: params.storageKey,
                tag: params.tag ?? "",
            });
            const skill = await stigmer.skill.pushFromExecutionArtifact(request);
            return {
                kind: "Skill",
                name: skill.metadata?.name ?? "",
                org: skill.metadata?.org ?? params.org,
                slug: skill.metadata?.slug ?? "",
            };
        }
        catch (err) {
            setError(toError(err));
            throw err;
        }
        finally {
            setIsApplying(false);
        }
    }, [stigmer]);
    return { applyYamlResource, pushSkillPackage, isApplying, error, clearError };
}
//# sourceMappingURL=useApplyResource.js.map