export interface TraceEventRow {
  rowId: string;
  seq: number | null;
  tone: "ok" | "blocked" | "warn" | "source";
  header: string;
  body: string | null;
  terminal?: boolean;
  bodyFormat?: "markdown" | "text";
}

type TraceEvent = Record<string, unknown>;

export function traceDisplayRows(trace: Record<string, unknown> = {}, events: TraceEvent[] = []): TraceEventRow[] {
  const rows: TraceEventRow[] = [];
  const renderedSourceEvents = new Set<string>();
  const renderedToolIdentities = new Set<string>();
  const assistantRows: AssistantRowState[] = [];
  let requestRendered = false;
  let setupRendered = false;
  let lastAssistantRowIndex = -1;
  let completionEvent: TraceEvent | null = null;
  for (let index = 0; index < events.length; index += 1) {
    const event = events[index];
    const sourceEventKey = traceSourceEventKey(event);
    if (sourceEventKey) {
      if (renderedSourceEvents.has(sourceEventKey)) continue;
      renderedSourceEvents.add(sourceEventKey);
    }
    if (!event || isNoisyTraceEvent(event)) continue;
    if (isToolTraceEvent(event)) {
      if (isSupersededToolStart(event, events, index)) continue;
      const identity = toolIdentity(event);
      if (identity) {
        if (renderedToolIdentities.has(identity)) continue;
        renderedToolIdentities.add(identity);
      }
      rows.push(traceToolCallRow(trace, event));
      continue;
    }
    if (isRequestTraceEvent(event)) {
      if (!requestRendered) {
        rows.push(traceRequestSummaryRow(event));
        requestRendered = true;
      }
      continue;
    }
    if (isSetupTraceEvent(event)) {
      if (!setupRendered) {
        rows.push(traceSetupSummaryRow(event));
        setupRendered = true;
      }
      continue;
    }
    if (isTerminalAssistantTraceEvent(event)) {
      const assistantRowIndex = upsertAssistantMessageRow(rows, assistantRows, trace, event, { terminal: true });
      if (assistantRowIndex >= 0) lastAssistantRowIndex = assistantRowIndex;
      continue;
    }
    if (isAssistantTraceEvent(event)) {
      const assistantRowIndex = upsertAssistantMessageRow(rows, assistantRows, trace, event, { terminal: false });
      if (assistantRowIndex >= 0) lastAssistantRowIndex = assistantRowIndex;
      continue;
    }
    if (isCompletionTraceEvent(event)) {
      completionEvent = event;
      continue;
    }
    rows.push(traceDisplayRow(trace, event));
  }
  if (completionEvent) {
    const finalResponseText = traceFinalResponseText(trace);
    if (finalResponseText) {
      lastAssistantRowIndex = upsertAuthoritativeFinalResponseRow(rows, assistantRows, completionEvent, finalResponseText);
    }
    const lastAssistantRow = lastAssistantRowIndex >= 0 ? rows[lastAssistantRowIndex] : undefined;
    if (lastAssistantRow) rows[lastAssistantRowIndex] = markAssistantRowTerminal(trace, lastAssistantRow, completionEvent);
    else rows.push(traceCompletionSummaryRow(trace, completionEvent));
  }
  return rows.length > 0 ? rows : events.map((event) => traceDisplayRow(trace, event));
}

export function renderTraceRowsMarkdown(rows: TraceEventRow[] = []): string {
  if (!Array.isArray(rows) || rows.length === 0) return `_No rendered trace rows were returned._`;
  return rows.map((row, index) => renderTraceRowMarkdown(row, index + 1)).join("\n\n");
}

export function renderTraceRowMarkdown(row: TraceEventRow, index = 1): string {
  if (!isToolTraceRow(row)) return renderTraceMessageRowMarkdown(row);
  const body = renderTraceToolDetailBody(row) || row.header || `trace row ${index}`;
  return [
    `- <details>`,
    `  <summary>${escapeHtml(`已运行 ${traceToolSummary(row)}`)}</summary>`,
    ``,
    indentTraceMarkdownBlock(traceMarkdownFence(row.bodyFormat === "markdown" ? "markdown" : "text", body)),
    ``,
    `  </details>`
  ].join("\n");
}

function renderTraceMessageRowMarkdown(row: TraceEventRow): string {
  const body = row.body?.trimEnd();
  if (body) return traceBoldMarkdown(body);
  return traceBoldMarkdown(row.header || `_No readable trace row body._`);
}

function isToolTraceRow(row: TraceEventRow): boolean {
  return row.rowId.startsWith("tool:") || /commandExecution/u.test(row.header);
}

function traceToolSummary(row: TraceEventRow): string {
  const firstLine = traceMarkdownPreviewLines(row.body).find((line) => !/^(stdout|stderr|exitCode|rowId|terminal):/iu.test(line.trim()));
  return compactTraceOneLine(stripTraceToolOutputFromSummary(firstLine || row.header || "tool call"), 90);
}

function stripTraceToolOutputFromSummary(value: string): string {
  return value.replace(/\s+(stdout:|stderr:|exitCode=).*$/isu, "").trim();
}

interface AssistantRowState {
  rowIndex: number;
  comparableText: string;
  sourceEvent: TraceEvent;
  derivedSnapshotSuffix?: boolean;
}

interface AssistantSnapshotDecision {
  action: "replace" | "append-suffix" | "keep-existing";
  suffixText?: string;
}

function traceToolCallRow(trace: Record<string, unknown>, event: TraceEvent): TraceEventRow {
  const command = cleanShellCommand(event.command);
  const status = traceStatusToken(event);
  const toolName = nonEmptyString(event.toolName) ?? readableTraceLabel(event).replace(/^item\//u, "");
  const body = traceToolCallBody(event, command);
  return {
    rowId: `tool:${event.itemId ?? event.seq ?? `${event.label ?? event.type ?? "tool"}:${event.createdAt ?? "unknown"}`}`,
    seq: numberOrNull(event.seq),
    tone: traceEventTone(event),
    header: `${traceClock(event.createdAt)} total=${formatTraceDuration(traceRelativeMs(trace, event))} ${status} ${toolName}`.trim(),
    body,
    bodyFormat: "text"
  };
}

function traceToolCallBody(event: TraceEvent, command: string | null): string | null {
  const lines = [
    command,
    traceDetailBlock("stdout", traceEventText(event, ["stdout", "stdoutText", "stdoutSummary"])),
    traceDetailBlock("stderr", traceEventText(event, ["stderr", "stderrText", "stderrSummary"])),
    command ? null : traceEventText(event, ["output", "outputText", "outputSummary"]),
    event.exitCode !== undefined ? `exitCode=${event.exitCode}` : null
  ].map(cleanTraceDetailText).filter(Boolean);
  return lines.length > 0 ? lines.join("\n") : null;
}

export function traceNoiseEventCount(events: TraceEvent[] = []): number {
  return Array.isArray(events) ? events.filter((event) => isNoisyTraceEvent(event)).length : 0;
}

function traceRequestSummaryRow(event: TraceEvent): TraceEventRow {
  const prompt = cleanTraceText(event.promptSummary ?? event.prompt ?? "");
  return {
    rowId: `trace-request:${event.seq ?? "accepted"}`,
    seq: numberOrNull(event.seq),
    tone: traceEventTone(event),
    header: `${traceClock(event.createdAt)}  请求接受${prompt ? `，提示词："${compactTraceOneLine(prompt, 120)}"` : ""}`,
    body: null
  };
}

function traceSetupSummaryRow(event: TraceEvent): TraceEventRow {
  const label = String(event.label ?? "");
  const parts = [
    /session:reused|thread\/resume/iu.test(label) ? "会话复用" : "会话就绪",
    /prompt:sent|sent prompt/iu.test(label) ? "提示词已发送" : null,
    /turn[:/]start|turn:started|turn\/start/iu.test(label) ? "轮次开始" : null
  ].filter(Boolean).join("，");
  return {
    rowId: `trace-setup:${event.seq ?? "session-turn"}`,
    seq: numberOrNull(event.seq),
    tone: "source",
    header: `${traceClock(event.createdAt)}  ${parts || "会话准备完成"}`,
    body: null
  };
}

function traceAssistantMessageRow(trace: Record<string, unknown>, event: TraceEvent, { terminal }: { terminal: boolean }): TraceEventRow {
  const text = cleanTraceText(event.message ?? event.outputSummary ?? assistantStreamText(trace, event) ?? "");
  const index = Number.isInteger(event.messageIndex) ? Number(event.messageIndex) : null;
  const count = Number.isInteger(event.messageCount) ? Number(event.messageCount) : null;
  return {
    rowId: `event:${event.seq ?? `${event.label ?? event.type ?? "assistant"}:${event.createdAt ?? "unknown"}`}`,
    seq: numberOrNull(event.seq),
    tone: "ok",
    header: `${traceClock(event.createdAt)}  ${terminal ? "助手最终消息" : "助手消息"}${index ? ` ${index}${count ? `/${count}` : ""}` : ""}`,
    terminal: terminal ? true : undefined,
    body: text || null,
    bodyFormat: "markdown"
  };
}

function upsertAssistantMessageRow(rows: TraceEventRow[], assistantRows: AssistantRowState[], trace: Record<string, unknown>, event: TraceEvent, options: { terminal: boolean }): number {
  const row = traceAssistantMessageRow(trace, event, options);
  const comparableText = comparableAssistantText(row.body);
  if (!comparableText) {
    rows.push(row);
    assistantRows.push({ rowIndex: rows.length - 1, comparableText, sourceEvent: event });
    return rows.length - 1;
  }

  for (let index = assistantRows.length - 1; index >= 0; index -= 1) {
    const state = assistantRows[index];
    if (!state) continue;
    const existingRow = rows[state.rowIndex];
    if (!existingRow) continue;
    if (state.comparableText === comparableText) {
      rows[state.rowIndex] = mergeAssistantRows(existingRow, row);
      state.sourceEvent = event;
      state.derivedSnapshotSuffix = false;
      return state.rowIndex;
    }
    if (comparableText.includes(state.comparableText)) {
      const previousIndex = comparableText.indexOf(state.comparableText);
      if (state.derivedSnapshotSuffix === true && previousIndex === 0) {
        rows[state.rowIndex] = mergeAssistantRows(row, existingRow);
        state.comparableText = comparableText;
        state.sourceEvent = event;
        state.derivedSnapshotSuffix = false;
        return state.rowIndex;
      }
      const snapshotDecision = assistantSnapshotDecision(comparableText, state.comparableText, event, state.sourceEvent);
      if (snapshotDecision.action === "append-suffix" && snapshotDecision.suffixText) {
        const suffixRow = { ...row, body: snapshotDecision.suffixText };
        rows.push(suffixRow);
        assistantRows.push({ rowIndex: rows.length - 1, comparableText: snapshotDecision.suffixText, sourceEvent: event, derivedSnapshotSuffix: true });
        return rows.length - 1;
      }
      if (snapshotDecision.action === "keep-existing") return state.rowIndex;
      rows[state.rowIndex] = mergeAssistantRows(row, existingRow);
      state.comparableText = comparableText;
      state.sourceEvent = event;
      state.derivedSnapshotSuffix = false;
      return state.rowIndex;
    }
    if (state.comparableText.includes(comparableText)) {
      rows[state.rowIndex] = mergeAssistantRows(existingRow, row);
      return state.rowIndex;
    }
  }

  rows.push(row);
  assistantRows.push({ rowIndex: rows.length - 1, comparableText, sourceEvent: event });
  return rows.length - 1;
}

function upsertAuthoritativeFinalResponseRow(rows: TraceEventRow[], assistantRows: AssistantRowState[], completionEvent: TraceEvent, finalText: string): number {
  const comparableText = comparableAssistantText(finalText);
  let matchedState: AssistantRowState | null = null;
  for (const state of assistantRows) {
    const row = rows[state.rowIndex];
    if (!row || row.bodyFormat !== "markdown") continue;
    row.terminal = undefined;
    if (!matchedState && state.comparableText === comparableText) matchedState = state;
  }
  if (matchedState) {
    const row = rows[matchedState.rowIndex];
    if (row) {
      rows[matchedState.rowIndex] = {
        ...row,
        body: finalText,
        terminal: true,
        tone: "ok",
        header: `${traceClock(completionEvent.createdAt)}  助手最终消息`
      };
      matchedState.comparableText = comparableText;
      matchedState.derivedSnapshotSuffix = false;
      return matchedState.rowIndex;
    }
  }
  rows.push({
    rowId: `trace-final-response:${completionEvent.seq ?? "completed"}`,
    seq: numberOrNull(completionEvent.seq),
    tone: "ok",
    header: `${traceClock(completionEvent.createdAt)}  助手最终消息`,
    terminal: true,
    body: finalText,
    bodyFormat: "markdown"
  });
  assistantRows.push({ rowIndex: rows.length - 1, comparableText, sourceEvent: completionEvent });
  return rows.length - 1;
}

function assistantSnapshotDecision(nextText: string, previousText: string, nextEvent: TraceEvent, previousEvent: TraceEvent): AssistantSnapshotDecision {
  if (!sameAssistantSnapshotIdentity(nextEvent, previousEvent)) return { action: "replace" };
  if (isAuthoritativeAssistantEvent(nextEvent) || isAuthoritativeAssistantEvent(previousEvent)) return { action: "replace" };
  const previousIndex = nextText.indexOf(previousText);
  if (previousIndex < 0) return { action: "replace" };
  const suffixText = nextText.slice(previousIndex + previousText.length).trim();
  if (suffixText && suffixText.length >= Math.max(80, previousText.length / 3)) return { action: "append-suffix", suffixText };
  if (previousIndex > 0 || !suffixText) return { action: "keep-existing" };
  return { action: "replace" };
}

function sameAssistantSnapshotIdentity(left: TraceEvent, right: TraceEvent): boolean {
  const leftItem = nonEmptyString(left.itemId ?? left.messageId ?? left.id);
  const rightItem = nonEmptyString(right.itemId ?? right.messageId ?? right.id);
  if (leftItem && rightItem) return leftItem === rightItem;
  return false;
}

function isAuthoritativeAssistantEvent(event: TraceEvent): boolean {
  return event.replyAuthority === true || event.final === true || event.terminal === true || String(event.status ?? "") === "completed";
}

function mergeAssistantRows(preferred: TraceEventRow, metadata: TraceEventRow): TraceEventRow {
  return {
    ...preferred,
    terminal: preferred.terminal || metadata.terminal ? true : undefined,
    header: metadata.terminal && !preferred.terminal ? metadata.header : preferred.header,
    tone: preferred.tone === "ok" || metadata.tone === "ok" ? "ok" : preferred.tone
  };
}

function comparableAssistantText(value: unknown): string {
  return cleanTraceText(value).replace(/\s+/gu, " ");
}

function traceFinalResponseText(trace: Record<string, unknown>): string | null {
  const response = trace.finalResponse && typeof trace.finalResponse === "object" ? trace.finalResponse as Record<string, unknown> : null;
  return nonEmptyString(response?.text ?? response?.content ?? response?.message);
}

function markAssistantRowTerminal(trace: Record<string, unknown>, row: TraceEventRow, completionEvent: TraceEvent): TraceEventRow {
  return {
    ...row,
    tone: "ok",
    terminal: true,
    header: `${row.header}，轮次完成（总耗时 ${formatTraceDuration(traceRelativeMs(trace, completionEvent))}）`
  };
}

function traceCompletionSummaryRow(trace: Record<string, unknown>, event: TraceEvent): TraceEventRow {
  return {
    rowId: `trace-completion:${event.seq ?? "turn"}`,
    seq: numberOrNull(event.seq),
    tone: traceEventTone(event),
    header: `${traceClock(event.createdAt)}  轮次完成（总耗时 ${formatTraceDuration(traceRelativeMs(trace, event))}）`,
    body: null
  };
}

function traceDisplayRow(trace: Record<string, unknown>, event: TraceEvent): TraceEventRow {
  const label = readableTraceLabel(event);
  return {
    rowId: `event:${event.seq ?? `${event.label ?? event.type ?? "event"}:${event.createdAt ?? "unknown"}`}`,
    seq: numberOrNull(event.seq),
    tone: traceEventTone(event),
    header: `${traceClock(event.createdAt)} total=${formatTraceDuration(traceRelativeMs(trace, event))} ${traceStatusToken(event)} ${label}`.trim(),
    body: traceDisplayBody(event)
  };
}

function assistantStreamText(trace: Record<string, unknown>, event: TraceEvent): string {
  const streams = Array.isArray(trace.assistantStreams) ? trace.assistantStreams.filter(isRecord) : [];
  const itemId = nonEmptyString(event.itemId ?? event.messageId ?? event.id);
  const matched = itemId ? streams.find((stream) => [stream.itemId, stream.messageId, stream.id].map(nonEmptyString).includes(itemId)) : null;
  return nonEmptyString(matched?.text ?? streams.at(-1)?.text) ?? "";
}

function isRequestTraceEvent(event: TraceEvent): boolean {
  const label = String(event.label ?? "");
  return label === "agentrun:request:accepted" || label === "request:accepted-short-connection" || label === "request:accepted" || label === "request:received";
}

function isSetupTraceEvent(event: TraceEvent): boolean {
  const label = String(event.label ?? "");
  return /^session:|^stdio:|^prompt:|^thread:|^turn:started|^turn:start|turn\/start|codex turn|tool:codex-app-server/iu.test(label) ||
    /^agentrun:backend:(codex-app-server-starting|initialize:completed|thread\/start|thread\/resume|thread\/started|turn\/start|turn\/started)/iu.test(label);
}

function isCompletionTraceEvent(event: TraceEvent): boolean {
  const label = String(event.label ?? "");
  return label.startsWith("turn:completed") || label.startsWith("result:completed") || label === "agentrun:backend:turn/completed" || label === "agentrun:terminal:completed" || label === "agentrun:result:completed";
}

function isAssistantTraceEvent(event: TraceEvent): boolean {
  const label = String(event.label ?? "");
  return label === "agentrun:assistant:message" || label === "assistant:message" || event.type === "assistant_message" || event.type === "assistant";
}

function isTerminalAssistantTraceEvent(event: TraceEvent): boolean {
  const label = String(event.label ?? "");
  if (label === "assistant:completed") return true;
  if (label === "agentrun:assistant:message") return event.replyAuthority === true || event.final === true;
  return event.type === "assistant_message" && (event.status === "completed" || event.final === true || event.terminal === true);
}

function isToolTraceEvent(event: TraceEvent): boolean {
  const label = String(event.label ?? "");
  const type = String(event.type ?? "");
  const toolName = String(event.toolName ?? "");
  return type === "tool_call" || toolName === "commandExecution" || /commandExecution|^agentrun:tool:/u.test(label);
}

function isToolStartTraceEvent(event: TraceEvent): boolean {
  const status = String(event.status ?? "").toLowerCase();
  const label = String(event.label ?? "");
  return status === "started" || /:started$|\/started$/u.test(label);
}

function isToolCompleteTraceEvent(event: TraceEvent): boolean {
  const status = String(event.status ?? "").toLowerCase();
  const label = String(event.label ?? "");
  return ["completed", "succeeded", "failed", "blocked", "timeout", "canceled", "cancelled"].includes(status) || /:completed$|\/completed$/u.test(label);
}

function toolIdentity(event: TraceEvent): string | null {
  return nonEmptyString(event.itemId ?? event.id ?? event.command);
}

function traceSourceEventKey(event: TraceEvent | null | undefined): string | null {
  if (!event || typeof event !== "object") return null;
  const source = nonEmptyString(event.source);
  const sourceSeq = nonEmptyString(event.sourceSeq);
  if (!source || !sourceSeq) return null;
  return `${source}:${sourceSeq}`;
}

function isSupersededToolStart(event: TraceEvent, events: TraceEvent[], index: number): boolean {
  if (!isToolStartTraceEvent(event)) return false;
  const identity = toolIdentity(event);
  if (!identity) return false;
  return events.slice(index + 1).some((candidate) => candidate && isToolTraceEvent(candidate) && isToolCompleteTraceEvent(candidate) && toolIdentity(candidate) === identity);
}

function isNoisyTraceEvent(event: TraceEvent): boolean {
  const label = String(event.label ?? "");
  if (isRequestTraceEvent(event) || isSetupTraceEvent(event) || isCompletionTraceEvent(event) || isTerminalAssistantTraceEvent(event) || isAssistantTraceEvent(event)) return false;
  if (/token_count|outputDelta:chunk/iu.test(label)) return true;
  if (/^agentrun:output:(stdout|stderr)$/u.test(label)) return true;
  if (/^agentrun:backend:(run-created|command-created|runner-job-created|thread\/status\/changed|thread\/tokenUsage\/updated|account\/rateLimits\/updated|remoteControl\/status\/changed|configWarning|codex-app-server-closed|codex-app-server-notifications-suppressed|session-updated|command-terminal|backend-turn-finished|item\/agentMessage:(started|completed)|thread\/goal\/cleared)$/u.test(label)) return true;
  return event.type === "event" && !event.outputSummary && !event.message && !event.errorCode;
}

function readableTraceLabel(event: TraceEvent): string {
  const label = String(event.label ?? `${event.type ?? "event"}:${event.status ?? "observed"}`);
  if (label === "request:accepted-short-connection") return "submit short-connection";
  if (label === "request:accepted") return "request accepted";
  if (label.startsWith("turn:completed")) return "turn completed";
  if (label.startsWith("result:completed")) return "result ready";
  return label.replace(/^tool:/u, "").replace(/^assistant:/u, "assistant ").replace(/:completed$/u, " completed").replace(/:started$/u, " started");
}

function traceDisplayBody(event: TraceEvent): string | null {
  const command = cleanShellCommand(event.command);
  const lines = [
    command,
    traceDetailBlock("stdout", traceEventText(event, ["stdout", "stdoutText", "stdoutSummary"])),
    traceDetailBlock("stderr", traceEventText(event, ["stderr", "stderrText", "stderrSummary"])),
    traceEventText(event, ["output", "outputText", "outputSummary"]),
    traceEventText(event, ["prompt", "promptText", "promptSummary"]),
    traceEventText(event, ["message"]),
    traceEventText(event, ["chunk"])
  ].map(cleanTraceDetailText).filter(Boolean);
  return lines.length > 0 ? lines.join("\n") : null;
}

function traceMarkdownPreviewLines(body: string | null | undefined): string[] {
  return String(body ?? "")
    .replace(/\r\n|\r/gu, "\n")
    .trim()
    .split("\n")
    .map((line) => line.trimEnd())
    .filter((line) => Boolean(line.trim()));
}

function renderTraceRowDetailBody(row: TraceEventRow): string {
  return [
    row.body?.trimEnd() ?? "",
    row.rowId ? `rowId: ${row.rowId}` : "",
    row.terminal === true ? "terminal: true" : ""
  ].filter(Boolean).join("\n");
}

function renderTraceToolDetailBody(row: TraceEventRow): string {
  return normalizeTraceToolDetailBody(renderTraceRowDetailBody(row));
}

function normalizeTraceToolDetailBody(value: string): string {
  return String(value ?? "")
    .replace(/\r\n|\r/gu, "\n")
    .replace(/[^\S\n]+(stdout:)[^\S\n]*/giu, "\n$1\n")
    .replace(/[^\S\n]+(stderr:)[^\S\n]*/giu, "\n$1\n")
    .replace(/[^\S\n]+(exitCode=)/giu, "\n$1")
    .replace(/\n{3,}/gu, "\n\n")
    .trimEnd();
}

function traceBoldMarkdown(value: string): string {
  const body = String(value ?? "").trimEnd();
  if (!body) return "";
  return body.split("\n").map((line) => {
    if (!line.trim()) return "";
    return `**${escapeMarkdownStrongText(line)}**`;
  }).join("\n");
}

function escapeMarkdownStrongText(value: string): string {
  return escapeHtml(value).replace(/\\/gu, "\\\\").replace(/\*/gu, "\\*");
}

function indentTraceMarkdownBlock(value: string): string {
  return String(value).split("\n").map((line) => `  ${line}`).join("\n");
}

function escapeHtml(value: string): string {
  return String(value).replace(/&/gu, "&amp;").replace(/</gu, "&lt;").replace(/>/gu, "&gt;");
}

function traceMarkdownFence(language: string, body: string): string {
  const fence = body.includes("```") ? "````" : "```";
  return `${fence}${language}\n${body.trimEnd()}\n${fence}`;
}

function traceStatusToken(event: TraceEvent): string {
  const status = String(event.status ?? "");
  if (status === "completed" || status === "succeeded") return "ok";
  if (["failed", "blocked", "error", "timeout", "canceled"].includes(status) || event.errorCode) return "fail";
  if (["started", "running", "accepted"].includes(status)) return "run";
  return status || "event";
}

function traceEventTone(event: TraceEvent): TraceEventRow["tone"] {
  const status = traceStatusToken(event);
  if (status === "ok") return "ok";
  if (status === "fail") return "blocked";
  if (status === "run") return "warn";
  return "source";
}

function traceClock(value: unknown): string {
  const date = new Date(String(value ?? ""));
  return Number.isNaN(date.getTime()) ? "--:--:--" : date.toISOString().slice(11, 19);
}

function traceRelativeMs(trace: Record<string, unknown>, event: TraceEvent): number {
  if (typeof event.elapsedMs === "number") return event.elapsedMs;
  const start = Date.parse(String(trace.startedAt ?? trace.createdAt ?? ""));
  const current = Date.parse(String(event.createdAt ?? ""));
  return Number.isNaN(start) || Number.isNaN(current) ? 0 : Math.max(0, current - start);
}

function formatTraceDuration(ms: number): string {
  const seconds = Math.floor(Math.max(0, Number(ms) || 0) / 1000);
  return [Math.floor(seconds / 3600), Math.floor((seconds % 3600) / 60), seconds % 60].map((part) => String(part).padStart(2, "0")).join(":");
}

function cleanTraceText(value: unknown): string {
  return String(value ?? "").replace(/\u0000/gu, "").replace(/\r\n|\r/gu, "\n").replace(/[ \t]{2,}/gu, " ").replace(/\n{3,}/gu, "\n\n").trim();
}

function cleanTraceDetailText(value: unknown): string {
  return String(value ?? "").replace(/\u0000/gu, "").replace(/\r\n|\r/gu, "\n").replace(/\n{4,}/gu, "\n\n\n").trim();
}

function traceEventText(event: TraceEvent, keys: string[]): string | null {
  for (const key of keys) {
    const value = event[key];
    if (value === undefined || value === null) continue;
    const body = cleanTraceDetailText(value);
    if (body) return body;
  }
  return null;
}

function traceDetailBlock(label: string, value: string | null): string | null {
  return value ? `${label}:\n${value}` : null;
}

function cleanShellCommand(value: unknown): string | null {
  const raw = cleanTraceDetailText(value);
  if (!raw) return null;
  const stripped = stripShellWrapper(raw);
  const unescaped = stripped.replace(/\\(["`$\\])/gu, "$1");
  return cleanTraceDetailText(unescaped);
}

function stripShellWrapper(value: string): string {
  const match = value.match(/^\s*(?:\/usr\/bin\/env\s+)?(?:\/bin\/sh|sh|bash|\/bin\/bash)\s+-lc\s+([\s\S]*)$/u);
  if (!match) return value;
  return unwrapShellArgument(match[1] ?? "");
}

function unwrapShellArgument(value: string): string {
  const text = value.trim();
  if (text.length >= 2) {
    const quote = text[0];
    if ((quote === "'" || quote === '"') && text[text.length - 1] === quote) {
      return text.slice(1, -1);
    }
  }
  return text;
}

function compactTraceOneLine(value: unknown, limit = 220): string {
  const text = cleanTraceText(value).replace(/\s+/gu, " ");
  return text.length <= limit ? text : `${text.slice(0, Math.max(0, limit - 3))}...`;
}

function numberOrNull(value: unknown): number | null {
  return Number.isInteger(value) ? Number(value) : null;
}

function nonEmptyString(value: unknown): string | null {
  const text = String(value ?? "").trim();
  return text ? text : null;
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return Boolean(value && typeof value === "object");
}
