<script setup lang="ts">
import { computed } from "vue";
import StatusBadge from "@/components/common/StatusBadge.vue";
import type { AgentRunProvenance, ChatMessage } from "@/types";
import { firstNonEmptyString } from "@/utils";

const props = defineProps<{ message: ChatMessage }>();

const trace = computed(() => props.message.runnerTrace ?? null);
const traceRecord = computed(() => recordValue(trace.value));
const agentRun = computed(() => asAgentRun(traceRecord.value?.agentRun ?? (props.message as Record<string, unknown>).agentRun));
const error = computed(() => normalizeSummaryError(props.message.error ?? traceRecord.value?.error));
const eventCount = computed(() => trace.value?.eventCount ?? trace.value?.events?.length ?? 0);

const errorTitle = computed(() => firstNonEmptyString(error.value?.code, error.value?.category, "失败原因"));
const errorMessage = computed(() => firstNonEmptyString(error.value?.message, error.value?.userMessage, error.value?.reason));

const rows = computed(() => [
  summaryRow("turnStatus", "Turn 状态", props.message.status),
  summaryRow("traceDetailStatus", "Trace 明细", firstNonEmptyString(trace.value?.status, trace.value?.traceStatus)),
  summaryRow("traceId", "Trace", props.message.traceId ?? trace.value?.traceId),
  summaryRow("sessionId", "Session", props.message.sessionId ?? trace.value?.sessionId),
  summaryRow("threadId", "Thread", props.message.threadId ?? trace.value?.threadId),
  summaryRow("runnerKind", "Runner", trace.value?.runnerKind ?? agentRun.value?.adapter),
  summaryRow("sessionMode", "Session Mode", trace.value?.sessionMode ?? agentRun.value?.backendProfile),
  summaryRow("waitingFor", "Waiting For", trace.value?.waitingFor),
  summaryRow("lastEvent", "Last Event", trace.value?.lastEventLabel),
  summaryRow("eventCount", "Events", eventCount.value > 0 ? eventCount.value : null),
  summaryRow("eventsCompacted", "Compacted", trace.value?.eventsCompacted === true ? "true" : null),
  summaryRow("fullTraceLoaded", "Full Trace", trace.value?.fullTraceLoaded === true ? "loaded" : null),
  summaryRow("runId", "AgentRun", agentRun.value?.runId),
  summaryRow("commandId", "Command", agentRun.value?.commandId),
  summaryRow("attemptId", "Attempt", agentRun.value?.attemptId),
  summaryRow("runnerId", "Runner ID", agentRun.value?.runnerId),
  summaryRow("jobName", "Job", agentRun.value?.jobName),
  summaryRow("namespace", "Namespace", agentRun.value?.namespace),
  summaryRow("terminalStatus", "Terminal", agentRun.value?.terminalStatus),
  summaryRow("errorCode", "Error Code", error.value?.code),
  summaryRow("errorCategory", "Error Category", error.value?.category),
  summaryRow("providerStatus", "Provider Status", error.value?.providerStatus)
].filter((row): row is { key: string; label: string; value: string } => Boolean(row)));

function asAgentRun(value: unknown): AgentRunProvenance | null {
  return value && typeof value === "object" ? value as AgentRunProvenance : null;
}

function recordValue(value: unknown): Record<string, unknown> | null {
  return value && typeof value === "object" ? value as Record<string, unknown> : null;
}

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

function normalizeSummaryError(value: unknown): Record<string, unknown> | null {
  if (!value) return null;
  if (typeof value === "string") return value.trim() ? { message: value.trim() } : null;
  return value && typeof value === "object" ? value as Record<string, unknown> : null;
}
</script>

<template>
  <details v-if="message.role === 'agent'" class="code-agent-status-summary" :open="message.status !== 'completed'">
    <summary>
      <span>Code Agent 状态摘要</span>
      <StatusBadge :status="message.status" />
    </summary>
    <div v-if="error" class="code-agent-error-summary">
      <strong>{{ errorTitle }}</strong>
      <p v-if="errorMessage">{{ errorMessage }}</p>
    </div>
    <dl v-if="rows.length > 0">
      <div v-for="row in rows" :key="row.key" class="code-agent-status-row" :data-status-row="row.key">
        <dt>{{ row.label }}</dt>
        <dd>{{ row.value }}</dd>
      </div>
    </dl>
  </details>
</template>
