<template>
  <div class="page-content">
    <div class="mb-5">
      <h2 class="text-xl font-semibold">LLM Trace</h2>
      <p class="text-g-500 mt-1 text-sm">查看应用与数字员工的一次请求如何经过检索、模型和工具调用；仅展示运行元数据，不保存正文。</p>
    </div>

    <div class="mb-4 flex flex-wrap items-center gap-3">
      <ElDatePicker v-model="range" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
      <ElSelect v-model="filter.trace_type" clearable placeholder="目标类型" class="!w-36"><ElOption label="AI 应用" value="application" /><ElOption label="数字员工" value="digital_employee" /></ElSelect>
      <ElInput v-model="filter.target_code" clearable placeholder="目标编码" class="!w-48" />
      <ElSelect v-model="filter.status" clearable placeholder="状态" class="!w-32"><ElOption label="运行中" value="running" /><ElOption label="成功" value="success" /><ElOption label="失败" value="error" /></ElSelect>
      <ElInput v-model="filter.request_id" clearable placeholder="Request ID" class="!w-56" />
      <ElButton type="primary" @click="load">查询</ElButton>
    </div>

    <ElTable v-loading="loading" :data="items" row-key="id">
      <ElTableColumn label="时间" min-width="180"><template #default="{ row }">{{ formatTime(row.started_at) }}</template></ElTableColumn>
      <ElTableColumn label="目标" min-width="190"><template #default="{ row }"><div>{{ row.trace_type === 'application' ? 'AI 应用' : '数字员工' }}</div><div class="text-g-500 text-xs">{{ row.target_code }}</div></template></ElTableColumn>
      <ElTableColumn label="状态" width="90"><template #default="{ row }"><ElTag :type="statusType(row.status)">{{ statusLabel(row.status) }}</ElTag></template></ElTableColumn>
      <ElTableColumn label="调用链" min-width="180"><template #default="{ row }">模型 {{ row.model_call_count }} · 工具 {{ row.tool_call_count }} · 检索 {{ row.retrieval_count }}</template></ElTableColumn>
      <ElTableColumn label="耗时" width="110"><template #default="{ row }">{{ row.latency_ms == null ? '—' : `${row.latency_ms} ms` }}</template></ElTableColumn>
      <ElTableColumn prop="request_id" label="Request ID" min-width="220" />
      <ElTableColumn label="操作" width="90" fixed="right"><template #default="{ row }"><ElButton link type="primary" @click="showDetail(row)">详情</ElButton></template></ElTableColumn>
    </ElTable>

    <ElDialog v-model="detailVisible" :title="`Trace · ${selected?.target_code ?? ''}`" width="980px">
      <template v-if="selected">
        <div class="mb-4 grid grid-cols-2 gap-3 md:grid-cols-4">
          <ElCard shadow="never"><div class="text-g-500 text-xs">状态</div><div class="mt-1 font-medium">{{ statusLabel(selected.status) }}</div></ElCard>
          <ElCard shadow="never"><div class="text-g-500 text-xs">总耗时</div><div class="mt-1 font-medium">{{ selected.latency_ms ?? '—' }} ms</div></ElCard>
          <ElCard shadow="never"><div class="text-g-500 text-xs">模型调用</div><div class="mt-1 font-medium">{{ selected.model_call_count }}</div></ElCard>
          <ElCard shadow="never"><div class="text-g-500 text-xs">Request ID</div><div class="mt-1 truncate font-medium" :title="selected.request_id">{{ selected.request_id }}</div></ElCard>
        </div>
        <ElAlert v-if="selected.error" class="mb-4" type="error" :closable="false" :title="selected.error" />
        <ElTable :data="selected.spans ?? []" row-key="id" max-height="480">
          <ElTableColumn label="类型" width="100"><template #default="{ row }"><ElTag :type="spanType(row.span_type)">{{ spanLabel(row.span_type) }}</ElTag></template></ElTableColumn>
          <ElTableColumn prop="name" label="名称" min-width="190" />
          <ElTableColumn label="模型 / Provider" min-width="180"><template #default="{ row }">{{ row.model || '—' }}<span v-if="row.provider_code" class="text-g-500 text-xs"> · {{ row.provider_code }}</span></template></ElTableColumn>
          <ElTableColumn label="状态" width="90"><template #default="{ row }"><ElTag :type="statusType(row.status)">{{ statusLabel(row.status) }}</ElTag></template></ElTableColumn>
          <ElTableColumn label="Token" width="130"><template #default="{ row }">{{ row.input_tokens || 0 }} + {{ row.output_tokens || 0 }}</template></ElTableColumn>
          <ElTableColumn label="耗时" width="110"><template #default="{ row }">{{ row.latency_ms == null ? '—' : `${row.latency_ms} ms` }}</template></ElTableColumn>
          <ElTableColumn prop="error" label="错误" min-width="220" show-overflow-tooltip />
        </ElTable>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
import { fetchTrace, fetchTraces, type Trace, type TraceSpan } from '@/api/traces'

const now = new Date()
const range = ref<[Date, Date]>([new Date(now.getTime() - 24 * 3600_000), now])
const filter = reactive({ trace_type: '', target_code: '', status: '', request_id: '' })
const items = ref<Trace[]>([])
const loading = ref(false)
const detailVisible = ref(false)
const selected = ref<Trace>()

async function load() {
  loading.value = true
  try {
    const result = await fetchTraces({ from: range.value[0].toISOString(), to: range.value[1].toISOString(), trace_type: filter.trace_type || undefined, target_code: filter.target_code || undefined, status: filter.status || undefined, request_id: filter.request_id || undefined, limit: 100 })
    items.value = result.items
  } finally { loading.value = false }
}
async function showDetail(row: Trace) { selected.value = await fetchTrace(row.id); detailVisible.value = true }
function formatTime(value: string) { return new Date(value).toLocaleString() }
function statusLabel(value: string) { return ({ running: '运行中', success: '成功', error: '失败' } as Record<string, string>)[value] ?? value }
function statusType(value: string) { return value === 'success' ? 'success' : value === 'error' ? 'danger' : 'warning' }
function spanLabel(value: TraceSpan['span_type']) { return ({ model: '模型', tool: '工具', retrieval: '检索' } as Record<string, string>)[value] ?? value }
function spanType(value: TraceSpan['span_type']) { return value === 'model' ? 'primary' : value === 'tool' ? 'warning' : 'info' }
onMounted(load)
</script>
