"use client";
import { useMemo } from "react";
import { ExecutionPhase } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/enum_pb";
import { isTerminalPhase } from "../execution/execution-phases";
/**
 * Returns the dedup key for an artifact. Uses `sandbox_path` when
 * available (stable filesystem identity within the session sandbox),
 * falling back to `name` for older artifacts that predate the field.
 */
function dedupKey(artifact) {
    return artifact.sandboxPath || artifact.name;
}
/**
 * Pure derivation hook that aggregates artifacts across all executions
 * in a session into a unified, deduplicated, alphabetically-sorted
 * list — like a file explorer showing the conversation's output.
 *
 * Follows the same `useMemo`-based pattern as
 * {@link useExecutionArtifacts}: no side effects, no data fetching.
 *
 * **Dedup semantics:** Artifacts are keyed by `sandbox_path` (the
 * original filesystem path in the agent sandbox). When multiple
 * executions produce an artifact at the same path, the latest
 * execution's version wins — matching filesystem overwrite semantics.
 *
 * **Sorting:** Entries are sorted alphabetically by display `name`
 * (case-insensitive). This matches the file-explorer mental model
 * where users scan by filename, not by creation order.
 *
 * **Name collision detection:** When two artifacts share the same
 * display `name` but differ in `sandbox_path`, both entries are
 * flagged with `hasNameCollision: true` so consumers can render path
 * context for disambiguation.
 *
 * @param executions - All executions for a session, in chronological
 *   order (as returned by `listBySession`). Pass both completed and
 *   active-stream executions.
 *
 * @example
 * ```tsx
 * const conv = useSessionConversation(sessionId, org);
 * const allExecutions = [
 *   ...conv.completedExecutions,
 *   ...(conv.activeStreamExecution ? [conv.activeStreamExecution] : []),
 * ];
 * const { artifacts, hasArtifacts } = useSessionArtifacts(allExecutions);
 * ```
 *
 * @see useExecutionArtifacts — single-execution artifact derivation
 * @see ArtifactsWidget — styled component that renders this data
 */
export function useSessionArtifacts(executions) {
    return useMemo(() => {
        const entryMap = new Map();
        for (const execution of executions) {
            const executionId = execution.metadata?.id ?? "";
            const phase = execution.status?.phase ??
                ExecutionPhase.EXECUTION_PHASE_UNSPECIFIED;
            const terminal = isTerminalPhase(phase);
            for (const artifact of execution.status?.artifacts ?? []) {
                const key = dedupKey(artifact);
                entryMap.set(key, {
                    artifact,
                    executionId,
                    isTerminal: terminal,
                    hasNameCollision: false,
                });
            }
        }
        const entries = Array.from(entryMap.values());
        entries.sort((a, b) => a.artifact.name.localeCompare(b.artifact.name, undefined, {
            sensitivity: "base",
        }));
        // Detect name collisions: entries that share a display name but
        // have different sandbox paths need path context for disambiguation.
        const nameCount = new Map();
        for (const entry of entries) {
            const lower = entry.artifact.name.toLowerCase();
            nameCount.set(lower, (nameCount.get(lower) ?? 0) + 1);
        }
        const result = entries.map((entry) => {
            const lower = entry.artifact.name.toLowerCase();
            if ((nameCount.get(lower) ?? 0) > 1) {
                return { ...entry, hasNameCollision: true };
            }
            return entry;
        });
        return {
            artifacts: result,
            hasArtifacts: result.length > 0,
            artifactCount: result.length,
        };
    }, [executions]);
}
//# sourceMappingURL=useSessionArtifacts.js.map