"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { memo } from "react";
import { WorkflowTaskKind } from "@stigmer/protos/ai/stigmer/agentic/workflow/v1/enum_pb";
import { cn } from "@stigmer/theme";
import { WorkflowTaskApprovalCard } from "./WorkflowTaskApprovalCard.js";
import { formatDuration, formatMicroUsd, formatBytes, formatTimestamp, formatMetaChips } from "./format-utils.js";
/**
 * Renders a single event in the workflow execution timeline.
 *
 * Dispatches on `event_type` to a type-specific renderer. Each event
 * is immutable after receipt, so this component is wrapped in
 * `React.memo` for efficient re-render skipping.
 *
 * @internal Not exported from the public SDK barrel — used only by
 * `WorkflowExecutionTimeline`.
 */
export const WorkflowExecutionTimelineEvent = memo(function WorkflowExecutionTimelineEvent({ event, onNavigateToAgentExecution, taskStates, onSubmitTaskApproval, taskApprovalSubmittingTaskNames, taskApprovalErrorsByTaskName, }) {
    const timestamp = formatTimestamp(event.occurredAt);
    const p = event.payload;
    switch (p.case) {
        // ── Execution lifecycle ──────────────────────────────────────────
        case "executionStarted":
            return (_jsxs(EventRow, { icon: _jsx(PlayIcon, {}), iconColor: "text-foreground", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-foreground", children: "Execution started" }), _jsxs("span", { className: "text-muted-foreground", children: [" · ", p.value.totalTasks, " tasks"] })] }));
        case "executionCompleted":
            return (_jsxs(EventRow, { icon: _jsx(CheckCircleIcon, {}), iconColor: "text-success", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-success", children: "Execution completed" }), _jsx(MetaChips, { duration: Number(p.value.durationMs), cost: p.value.totalCostMicros, tokens: p.value.totalTokens })] }));
        case "executionFailed":
            return (_jsxs(EventRow, { icon: _jsx(XCircleIcon, {}), iconColor: "text-destructive", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-destructive", children: "Execution failed" }), p.value.failedTaskName && (_jsxs("span", { className: "text-muted-foreground", children: [" · ", "task: ", p.value.failedTaskName] })), p.value.error && (_jsx("p", { className: "mt-1 text-xs text-destructive/80", children: p.value.error }))] }));
        case "executionPaused":
            return (_jsxs(EventRow, { icon: _jsx(PauseCircleIcon, {}), iconColor: "text-muted-foreground", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-muted-foreground", children: "Execution paused" }), p.value.reason && _jsxs("span", { className: "text-muted-foreground", children: [" · ", p.value.reason] })] }));
        case "executionResumed":
            return (_jsxs(EventRow, { icon: _jsx(PlayIcon, {}), iconColor: "text-foreground", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-foreground", children: "Execution resumed" }), p.value.resumedBy && _jsxs("span", { className: "text-muted-foreground", children: [" · ", "by ", p.value.resumedBy] })] }));
        case "executionCancelled":
            return (_jsxs(EventRow, { icon: _jsx(XCircleIcon, {}), iconColor: "text-muted-foreground", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-muted-foreground", children: "Execution cancelled" }), p.value.reason && _jsxs("span", { className: "text-muted-foreground", children: [" · ", p.value.reason] })] }));
        case "executionTerminated":
            return (_jsxs(EventRow, { icon: _jsx(StopCircleIcon, {}), iconColor: "text-destructive", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-destructive", children: "Execution terminated" }), p.value.reason && _jsxs("span", { className: "text-muted-foreground", children: [" · ", p.value.reason] })] }));
        // ── Task lifecycle ───────────────────────────────────────────────
        case "taskStarted":
            return (_jsxs(EventRow, { icon: _jsx(ArrowRightIcon, {}), iconColor: "text-foreground", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-foreground", children: event.taskName }), _jsx(KindBadge, { kind: p.value.taskKind }), p.value.attemptNumber > 1 && (_jsxs("span", { className: "text-xs text-muted-foreground", children: ["(attempt ", p.value.attemptNumber, ")"] }))] }));
        case "taskCompleted":
            return (_jsxs(EventRow, { icon: _jsx(CheckIcon, {}), iconColor: "text-success", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-foreground", children: event.taskName }), _jsx("span", { className: "text-xs text-success", children: "completed" }), _jsx(MetaChips, { duration: Number(p.value.durationMs), cost: p.value.costMicros, tokens: p.value.tokensUsed })] }));
        case "taskFailed":
            return (_jsxs(EventRow, { icon: _jsx(XIcon, {}), iconColor: "text-destructive", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-foreground", children: event.taskName }), _jsx("span", { className: "text-xs text-destructive", children: "failed" }), p.value.willRetry && (_jsx("span", { className: "text-xs text-muted-foreground", children: "(will retry)" })), p.value.error && (_jsx("p", { className: "mt-1 text-xs text-destructive/80", children: p.value.error }))] }));
        case "taskSkipped":
            return (_jsxs(EventRow, { icon: _jsx(SkipIcon, {}), iconColor: "text-muted-foreground", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-muted-foreground", children: event.taskName }), _jsx("span", { className: "text-xs text-muted-foreground", children: "skipped" }), p.value.reason && (_jsxs("span", { className: "text-xs text-muted-foreground", children: [" · ", p.value.reason] }))] }));
        case "taskRetrying":
            return (_jsxs(EventRow, { icon: _jsx(RetryIcon, {}), iconColor: "text-muted-foreground", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-foreground", children: event.taskName }), _jsxs("span", { className: "text-xs text-muted-foreground", children: ["retrying (attempt ", p.value.nextAttempt, ")"] }), p.value.delayMs > BigInt(0) && (_jsxs("span", { className: "text-xs text-muted-foreground", children: ["after ", formatDuration(Number(p.value.delayMs))] }))] }));
        // ── Agent call ───────────────────────────────────────────────────
        case "agentCallStarted":
            return (_jsxs(EventRow, { icon: _jsx(AgentIcon, {}), iconColor: "text-foreground", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-foreground", children: event.taskName }), _jsxs("span", { className: "text-xs text-muted-foreground", children: ["agent: ", p.value.agentSlug] }), onNavigateToAgentExecution && p.value.childExecutionId && (_jsx("button", { type: "button", onClick: () => onNavigateToAgentExecution(p.value.childExecutionId), className: "text-xs text-primary hover:underline", children: "View execution" }))] }));
        case "agentCallProgress":
            return (_jsxs(EventRow, { icon: _jsx(AgentIcon, {}), iconColor: "text-muted-foreground", timestamp: timestamp, children: [_jsx("span", { className: "text-foreground", children: event.taskName }), _jsxs("span", { className: "text-xs text-muted-foreground", children: [p.value.messagesCount, " msgs \u00B7 ", p.value.toolCallsCount, " tools", p.value.currentToolName ? ` · ${p.value.currentToolName}` : ""] })] }));
        case "agentCallCompleted":
            return (_jsxs(EventRow, { icon: p.value.error ? _jsx(XIcon, {}) : _jsx(CheckIcon, {}), iconColor: p.value.error ? "text-destructive" : "text-success", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-foreground", children: event.taskName }), _jsxs("span", { className: cn("text-xs", p.value.error ? "text-destructive" : "text-success"), children: ["agent ", p.value.error ? "failed" : "completed"] }), _jsx(MetaChips, { duration: Number(p.value.durationMs), cost: p.value.costMicros, tokens: p.value.tokensConsumed }), p.value.error && (_jsx("p", { className: "mt-1 text-xs text-destructive/80", children: p.value.error }))] }));
        // ── Approval ─────────────────────────────────────────────────────
        case "approvalRequested": {
            const isHumanInput = !p.value.toolCallId;
            const isWaiting = taskStates?.get(event.taskName)?.status === "waiting_approval";
            const showCard = isWaiting && isHumanInput && onSubmitTaskApproval;
            return (_jsxs(EventRow, { icon: _jsx(ShieldIcon, {}), iconColor: "text-warning", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-warning", children: "Approval requested" }), !showCard && p.value.prompt && (_jsx("p", { className: "mt-1 text-xs text-foreground", children: p.value.prompt })), p.value.approvers.length > 0 && (_jsxs("p", { className: "text-xs text-muted-foreground", children: ["Approvers: ", p.value.approvers.join(", ")] })), p.value.timeoutSeconds > 0 && (_jsxs("p", { className: "text-xs text-muted-foreground", children: ["Timeout: ", formatDuration(p.value.timeoutSeconds * 1000)] })), showCard && (_jsx(WorkflowTaskApprovalCard, { taskName: event.taskName, prompt: p.value.prompt, outcomes: (p.value.outcomes ?? []).map((o) => ({
                            name: o.name,
                            label: o.label,
                        })), formSchema: p.value.formSchema
                            ? p.value.formSchema
                            : undefined, onSubmit: onSubmitTaskApproval, isSubmitting: taskApprovalSubmittingTaskNames?.has(event.taskName) ?? false, error: taskApprovalErrorsByTaskName?.get(event.taskName) ?? null }))] }));
        }
        case "approvalResolved":
            return (_jsxs(EventRow, { icon: _jsx(ShieldIcon, {}), iconColor: "text-success", timestamp: timestamp, children: [_jsx("span", { className: "font-medium text-foreground", children: "Approval resolved" }), _jsxs("span", { className: "text-xs text-muted-foreground", children: ["by ", p.value.resolvedBy] }), p.value.comment && (_jsxs("p", { className: "mt-1 text-xs text-muted-foreground italic", children: ["\"", p.value.comment, "\""] }))] }));
        // ── Budget ───────────────────────────────────────────────────────
        case "budgetCheckpoint":
            return (_jsxs(EventRow, { icon: _jsx(CoinIcon, {}), iconColor: p.value.thresholdBreached ? "text-warning" : "text-muted-foreground", timestamp: timestamp, children: [_jsx("span", { className: "text-foreground", children: "Budget checkpoint" }), _jsxs("span", { className: "text-xs text-muted-foreground", children: [formatMicroUsd(p.value.costConsumedMicros), " consumed", p.value.costRemainingMicros >= BigInt(0) && (_jsxs(_Fragment, { children: [" \u00B7 ", formatMicroUsd(p.value.costRemainingMicros), " remaining"] }))] }), p.value.thresholdBreached && (_jsx("span", { className: "text-xs font-medium text-warning", children: "threshold breached" }))] }));
        // ── Signals / events ─────────────────────────────────────────────
        case "signalReceived":
            return (_jsxs(EventRow, { icon: _jsx(SignalIcon, {}), iconColor: "text-muted-foreground", timestamp: timestamp, children: [_jsx("span", { className: "text-foreground", children: "Signal received" }), _jsx("span", { className: "text-xs text-muted-foreground", children: p.value.signalName })] }));
        case "eventEmitted":
            return (_jsxs(EventRow, { icon: _jsx(EmitIcon, {}), iconColor: "text-muted-foreground", timestamp: timestamp, children: [_jsx("span", { className: "text-foreground", children: "Event emitted" }), _jsx("span", { className: "text-xs text-muted-foreground", children: p.value.eventType })] }));
        // ── Artifacts ────────────────────────────────────────────────────
        case "artifactCreated":
            return (_jsxs(EventRow, { icon: _jsx(FileIcon, {}), iconColor: "text-muted-foreground", timestamp: timestamp, children: [_jsx("span", { className: "text-foreground", children: "Artifact created" }), _jsxs("span", { className: "text-xs text-muted-foreground", children: [p.value.displayName, " \u00B7 ", p.value.contentType, " \u00B7 ", formatBytes(p.value.sizeBytes)] })] }));
        default:
            return null;
    }
});
// ---------------------------------------------------------------------------
// Shared layout
// ---------------------------------------------------------------------------
function EventRow({ icon, iconColor, timestamp, children, }) {
    return (_jsxs("div", { className: "flex items-start gap-3 px-4 py-2 hover:bg-muted/30", role: "listitem", children: [_jsx("span", { className: cn("mt-0.5 flex size-4 shrink-0 items-center justify-center", iconColor), "aria-hidden": "true", children: icon }), _jsx("div", { className: "flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-0.5 text-xs", children: children }), _jsx("span", { className: "shrink-0 text-[10px] tabular-nums text-muted-foreground", children: timestamp })] }));
}
function KindBadge({ kind }) {
    const label = TASK_KIND_SHORT.get(kind) ?? kindToString(kind);
    return (_jsx("span", { className: "shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground", children: label }));
}
function MetaChips({ duration, cost, tokens, }) {
    const text = formatMetaChips({ durationMs: duration, costMicros: cost, tokens });
    if (!text)
        return null;
    return _jsx("span", { className: "text-xs text-muted-foreground", children: text });
}
// ---------------------------------------------------------------------------
// Icons (minimal inline SVGs — no external deps per DD-004)
// ---------------------------------------------------------------------------
function PlayIcon() {
    return _jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "currentColor", children: _jsx("path", { d: "M3 2l7 4-7 4V2z" }) });
}
function CheckCircleIcon() {
    return _jsxs("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", children: [_jsx("circle", { cx: "6", cy: "6", r: "4.5" }), _jsx("path", { d: "M4 6l1.5 1.5L8 5" })] });
}
function XCircleIcon() {
    return _jsxs("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", children: [_jsx("circle", { cx: "6", cy: "6", r: "4.5" }), _jsx("path", { d: "M4.5 4.5l3 3M7.5 4.5l-3 3" })] });
}
function PauseCircleIcon() {
    return _jsxs("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", children: [_jsx("circle", { cx: "6", cy: "6", r: "4.5" }), _jsx("path", { d: "M5 4.5v3M7 4.5v3" })] });
}
function StopCircleIcon() {
    return _jsxs("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", children: [_jsx("circle", { cx: "6", cy: "6", r: "4.5" }), _jsx("rect", { x: "4", y: "4", width: "4", height: "4", rx: "0.5", fill: "currentColor" })] });
}
function ArrowRightIcon() {
    return _jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", children: _jsx("path", { d: "M2 6h8M7 3l3 3-3 3" }) });
}
function CheckIcon() {
    return _jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", children: _jsx("path", { d: "M2.5 6L5 8.5L9.5 3.5" }) });
}
function XIcon() {
    return _jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", children: _jsx("path", { d: "M3 3l6 6M9 3l-6 6" }) });
}
function SkipIcon() {
    return _jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", children: _jsx("path", { d: "M2 3l4 3-4 3V3zM7 3l4 3-4 3V3z" }) });
}
function RetryIcon() {
    return _jsxs("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", children: [_jsx("path", { d: "M2 6a4 4 0 117 2.5" }), _jsx("path", { d: "M2 2v4h4" })] });
}
function AgentIcon() {
    return _jsxs("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", children: [_jsx("circle", { cx: "6", cy: "4", r: "2" }), _jsx("path", { d: "M2 10a4 4 0 018 0" })] });
}
function ShieldIcon() {
    return _jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", children: _jsx("path", { d: "M6 1L2 3v3c0 2.5 1.5 4 4 5 2.5-1 4-2.5 4-5V3L6 1z" }) });
}
function CoinIcon() {
    return _jsxs("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", children: [_jsx("circle", { cx: "6", cy: "6", r: "4.5" }), _jsx("path", { d: "M6 3v6M4.5 4.5h2a1 1 0 010 2H5a1 1 0 000 2h2" })] });
}
function SignalIcon() {
    return _jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", children: _jsx("path", { d: "M6 8v2M4 6l2 2 2-2M2 4l4 4 4-4" }) });
}
function EmitIcon() {
    return _jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", children: _jsx("path", { d: "M6 2v6M3 5l3 3 3-3M3 10h6" }) });
}
function FileIcon() {
    return _jsxs("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", children: [_jsx("path", { d: "M7 1H3a1 1 0 00-1 1v8a1 1 0 001 1h6a1 1 0 001-1V4L7 1z" }), _jsx("path", { d: "M7 1v3h3" })] });
}
// ---------------------------------------------------------------------------
// Formatting helpers
// ---------------------------------------------------------------------------
const TASK_KIND_SHORT = new Map([
    [WorkflowTaskKind.agent_call, "agent_call"],
    [WorkflowTaskKind.llm_call, "llm_call"],
    [WorkflowTaskKind.http_call, "http_call"],
    [WorkflowTaskKind.grpc_call, "grpc_call"],
    [WorkflowTaskKind.transform, "transform"],
    [WorkflowTaskKind.human_input, "human_input"],
    [WorkflowTaskKind.validate, "validate"],
    [WorkflowTaskKind.emit_event, "emit_event"],
    [WorkflowTaskKind.notification, "notification"],
    [WorkflowTaskKind.eval, "eval"],
    [WorkflowTaskKind.switch_case, "switch"],
    [WorkflowTaskKind.for_each, "for_each"],
    [WorkflowTaskKind.fork, "fork"],
    [WorkflowTaskKind.listen, "listen"],
    [WorkflowTaskKind.wait, "wait"],
]);
function kindToString(kind) {
    const entry = Object.entries(WorkflowTaskKind).find(([, v]) => v === kind && typeof v === "number");
    return entry?.[0] ?? "unknown";
}
//# sourceMappingURL=WorkflowExecutionTimelineEvent.js.map