<template>
  <div class="page-content">
    <div class="mb-5">
      <h2 class="text-xl font-semibold">智能体会话</h2>
      <p class="text-g-500 mt-1 text-sm">按会话聚合 AI 应用与数字员工请求；仅展示运行元数据和 Trace 入口，不展示对话正文。</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" />
      <ElInput v-model="filter.session_id" clearable placeholder="会话 ID" class="!w-64" />
      <ElButton type="primary" @click="load">查询</ElButton>
    </div>

    <ElTable v-loading="loading" :data="items" row-key="id">
      <ElTableColumn label="类型 / 目标" min-width="180"><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="会话 ID" min-width="260" show-overflow-tooltip><template #default="{ row }"><span :title="row.id">{{ row.id }}</span></template></ElTableColumn>
      <ElTableColumn label="Trace" width="90"><template #default="{ row }">{{ row.trace_count }}</template></ElTableColumn>
      <ElTableColumn label="调用统计" min-width="220"><template #default="{ row }">模型 {{ row.model_call_count }} · 工具 {{ row.tool_call_count }} · 检索 {{ row.retrieval_count }}</template></ElTableColumn>
      <ElTableColumn label="最近状态" width="110"><template #default="{ row }"><ElTag :type="statusType(row.latest_status)">{{ statusLabel(row.latest_status) }}</ElTag></template></ElTableColumn>
      <ElTableColumn label="最近活动" min-width="180"><template #default="{ row }">{{ formatTime(row.updated_at) }}</template></ElTableColumn>
      <ElTableColumn label="操作" width="120" fixed="right"><template #default="{ row }"><ElButton link type="primary" @click="showTrace(row)">查看 Trace</ElButton></template></ElTableColumn>
    </ElTable>

    <ElDialog v-model="detailVisible" :title="`最近 Trace · ${selectedTrace?.target_code ?? ''}`" width="980px">
      <template v-if="selectedTrace">
        <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">{{ selectedTrace.trace_type === 'application' ? 'AI 应用' : '数字员工' }}</div></ElCard>
          <ElCard shadow="never"><div class="text-g-500 text-xs">状态</div><div class="mt-1 font-medium">{{ statusLabel(selectedTrace.status) }}</div></ElCard>
          <ElCard shadow="never"><div class="text-g-500 text-xs">总耗时</div><div class="mt-1 font-medium">{{ selectedTrace.latency_ms ?? '—' }} ms</div></ElCard>
          <ElCard shadow="never"><div class="text-g-500 text-xs">Request ID</div><div class="mt-1 truncate font-medium" :title="selectedTrace.request_id">{{ selectedTrace.request_id }}</div></ElCard>
        </div>
        <ElAlert v-if="selectedTrace.error" class="mb-4" type="error" :closable="false" :title="selectedTrace.error" />
        <ElTable :data="selectedTrace.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 { fetchAgentSessions, type AgentSession } from '@/api/agent-sessions'
import { fetchTrace, type Trace, type TraceSpan } from '@/api/traces'

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

async function load() {
  loading.value = true
  try {
    const result = await fetchAgentSessions({ from: range.value[0].toISOString(), to: range.value[1].toISOString(), trace_type: filter.trace_type || undefined, target_code: filter.target_code || undefined, session_id: filter.session_id || undefined, limit: 100 })
    items.value = result.items
  } finally { loading.value = false }
}
async function showTrace(row: AgentSession) { selectedTrace.value = await fetchTrace(row.latest_trace_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>
