import type { ChatMessage } from "@/types";

export interface WorkbenchTraceTimelinePolicy {
  autoExpandRunning?: boolean;
  autoCollapseTerminal?: boolean;
}

export function traceLifecycleExpanded(message: ChatMessage, policy: WorkbenchTraceTimelinePolicy = {}): boolean | null {
  if (message.role !== "agent") return null;
  if (message.traceAutoLifecycle === "running") return policy.autoExpandRunning === true ? true : null;
  if (message.traceAutoLifecycle === "terminal") return policy.autoCollapseTerminal === true ? false : null;
  return policy.autoExpandRunning === true && isTraceActiveStatus(message.status) ? true : null;
}

function normalizeTraceStatus(value: unknown): string | null {
  const text = String(value ?? "").trim().toLowerCase().replace(/_/gu, "-");
  return text || null;
}

function isTraceActiveStatus(status: string): boolean {
  return ["accepted", "pending", "processing", "running", "busy", "creating", "queued"].includes(status);
}
