"use client";
import { useCallback, useMemo } from "react";
import { create } from "@bufbuild/protobuf";
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { StigmerError } from "@stigmer/sdk";
import { ListSkillVersionsInputSchema, } from "@stigmer/protos/ai/stigmer/agentic/skill/v1/io_pb";
import { useStigmer } from "../hooks";
import { useFetch } from "../internal/useFetch";
// gRPC/Connect Code.Unimplemented = 12
const CODE_UNIMPLEMENTED = 12;
// ---------------------------------------------------------------------------
// Hook implementation
// ---------------------------------------------------------------------------
/**
 * Data hook that fetches version history for a skill.
 *
 * Calls the `listVersions` RPC via the SDK client and maps the response
 * to generic {@link VersionEntry} objects for the `VersionTimeline`
 * component.
 *
 * **Graceful degradation**: If the backend returns UNIMPLEMENTED (the
 * RPC handler hasn't been deployed yet), the hook treats it as an empty
 * response — `versions` is `[]` and `isEmpty` is `true`. No error is
 * surfaced to the consumer. This enables the frontend to ship ahead of
 * the backend without visual breakage.
 *
 * Pass `null` for `org` or `slug` to skip fetching (stable no-op).
 *
 * @example
 * ```tsx
 * const { versions, isEmpty, isLoading } = useSkillVersions("acme", "code-style-guide");
 *
 * if (!isEmpty) {
 *   return <VersionTimeline entries={versions} />;
 * }
 * ```
 */
export function useSkillVersions(org, slug) {
    const stigmer = useStigmer();
    const { data: rawVersions, isLoading, error, refetch, } = useFetch(org && slug
        ? async () => {
            try {
                const request = create(ListSkillVersionsInputSchema, {
                    org,
                    slug,
                });
                const response = await stigmer.skill.listVersions(request);
                return response.versions;
            }
            catch (err) {
                if (isUnimplemented(err))
                    return [];
                throw err;
            }
        }
        : null, [org, slug, stigmer], []);
    const versions = useMemo(() => rawVersions.map(mapProtoToVersionEntry), [rawVersions]);
    const artifactKeyMap = useMemo(() => {
        const map = new Map();
        for (const entry of rawVersions) {
            if (entry.versionHash && entry.artifactStorageKey) {
                map.set(entry.versionHash, entry.artifactStorageKey);
            }
        }
        return map;
    }, [rawVersions]);
    const getArtifactKey = useCallback((versionHash) => artifactKeyMap.get(versionHash) ?? null, [artifactKeyMap]);
    const isEmpty = versions.length === 0;
    return useMemo(() => ({ versions, isEmpty, isLoading, error, refetch, getArtifactKey }), [versions, isEmpty, isLoading, error, refetch, getArtifactKey]);
}
// ---------------------------------------------------------------------------
// Proto → generic mapping
// ---------------------------------------------------------------------------
function mapProtoToVersionEntry(proto) {
    return {
        id: proto.versionHash,
        timestamp: proto.pushedAt ? timestampDate(proto.pushedAt) : new Date(0),
        actor: proto.pushedBy
            ? {
                id: proto.pushedBy.id,
                avatar: proto.pushedBy.avatar || undefined,
                displayName: undefined,
            }
            : undefined,
        label: proto.versionHash.slice(0, 12),
        sublabel: proto.message || undefined,
        isCurrent: proto.isCurrent,
        tag: proto.tag || undefined,
        gitProvenance: proto.gitProvenance
            ? {
                remoteUrl: proto.gitProvenance.remoteUrl,
                ref: proto.gitProvenance.ref,
                commit: proto.gitProvenance.commit,
            }
            : undefined,
    };
}
// ---------------------------------------------------------------------------
// Error detection
// ---------------------------------------------------------------------------
function isUnimplemented(err) {
    return err instanceof StigmerError && err.connectCode === CODE_UNIMPLEMENTED;
}
//# sourceMappingURL=useSkillVersions.js.map