export const TRACE_STATUS_LABELS = {
  succeeded: '成功',
  failed: '失败',
  blocked: '阻断',
  running: '运行中'
}

export const TRACE_SOURCE_LABELS = {
  user_message: '用户消息',
  schedule: '定时任务',
  system_event: '系统事件'
}

export function normalizeTraceListItem(item = {}) {
  const runId = normalizeText(item.run_id || item.runId)
  return {
    runId,
    conversationId: normalizeText(item.conversation_id || item.conversationId),
    agent: normalizeText(item.agent) || 'orchestrator',
    source: normalizeText(item.source),
    sourceLabel: TRACE_SOURCE_LABELS[normalizeText(item.source)] || normalizeText(item.source) || '未知来源',
    status: normalizeText(item.status) || 'unknown',
    statusLabel: TRACE_STATUS_LABELS[normalizeText(item.status)] || normalizeText(item.status) || '未知',
    scenario: normalizeText(item.scenario),
    intent: normalizeText(item.intent),
    title: normalizeText(item.title) || runId,
    summary: normalizeText(item.summary),
    eventCount: Number(item.event_count || item.eventCount || 0),
    toolCallCount: Number(item.tool_call_count || item.toolCallCount || 0),
    failedToolCallCount: Number(item.failed_tool_call_count || item.failedToolCallCount || 0),
    startedAt: normalizeText(item.started_at || item.startedAt),
    finishedAt: normalizeText(item.finished_at || item.finishedAt),
    durationMs: Number(item.duration_ms || item.durationMs || 0)
  }
}

export function normalizeTraceDetail(payload = {}) {
  const run = payload.run || {}
  const events = Array.isArray(payload.events)
    ? payload.events.map(normalizeTraceEvent)
    : []

  return {
    runId: normalizeText(run.run_id || run.runId),
    conversationId: normalizeText(payload.conversation_id || payload.conversationId),
    agent: normalizeText(run.agent),
    source: normalizeText(run.source),
    status: normalizeText(run.status),
    summary: normalizeText(run.result_summary || run.resultSummary),
    errorMessage: normalizeText(run.error_message || run.errorMessage),
    routeJson: run.route_json || run.routeJson || {},
    ontologyJson: run.ontology_json || run.ontologyJson || {},
    semanticParse: payload.semantic_parse || payload.semanticParse || run.semantic_parse || run.semanticParse || null,
    toolCalls: Array.isArray(payload.tool_calls || payload.toolCalls)
      ? payload.tool_calls || payload.toolCalls
      : [],
    conversationMessages: Array.isArray(payload.conversation_messages || payload.conversationMessages)
      ? payload.conversation_messages || payload.conversationMessages
      : [],
    fallbackGenerated: Boolean(payload.fallback_generated || payload.fallbackGenerated),
    events
  }
}

export function normalizeTraceEvent(event = {}) {
  const status = normalizeText(event.status) || 'unknown'
  return {
    id: normalizeText(event.id),
    runId: normalizeText(event.run_id || event.runId),
    sequence: Number(event.sequence || 0),
    stage: normalizeText(event.stage),
    eventName: normalizeText(event.event_name || event.eventName),
    title: normalizeText(event.title),
    summary: normalizeText(event.summary),
    status,
    statusLabel: TRACE_STATUS_LABELS[status] || status,
    inputJson: event.input_json || event.inputJson || {},
    outputJson: event.output_json || event.outputJson || {},
    errorMessage: normalizeText(event.error_message || event.errorMessage),
    startedAt: normalizeText(event.started_at || event.startedAt),
    finishedAt: normalizeText(event.finished_at || event.finishedAt),
    durationMs: Number(event.duration_ms || event.durationMs || 0)
  }
}

export function resolveTraceStatusTone(status) {
  const normalized = normalizeText(status)
  if (normalized === 'succeeded') return 'success'
  if (normalized === 'failed') return 'danger'
  if (normalized === 'blocked') return 'warning'
  if (normalized === 'running') return 'info'
  return 'muted'
}

export function formatTraceDateTime(value) {
  const normalized = normalizeText(value)
  if (!normalized) return '-'
  const date = new Date(normalized)
  return Number.isNaN(date.getTime())
    ? normalized
    : date.toLocaleString('zh-CN', { hour12: false })
}

export function formatTraceDuration(value) {
  const durationMs = Number(value || 0)
  if (!Number.isFinite(durationMs) || durationMs <= 0) {
    return '0ms'
  }
  if (durationMs < 1000) {
    return `${Math.round(durationMs)}ms`
  }
  return `${(durationMs / 1000).toFixed(2)}s`
}

export function formatTraceJson(value) {
  try {
    return JSON.stringify(value || {}, null, 2)
  } catch {
    return String(value || '')
  }
}

function normalizeText(value) {
  return String(value || '').trim()
}
