<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import StatusBadge from "@/components/common/StatusBadge.vue";
import { useCaseRunStore } from "@/stores/caserun";
import { formatTimestamp } from "@/stores/workbench-live";

const caserun = useCaseRunStore();
const selectedCaseId = ref("");
let pollTimer: ReturnType<typeof setInterval> | null = null;

const runStatus = computed(() => caserun.currentRun?.status ?? "idle");
const statusTone = computed(() => {
  if (runStatus.value === "completed") return "ok";
  if (runStatus.value === "failed") return "error";
  if (runStatus.value === "running" || runStatus.value === "queued") return "pending";
  return "pending";
});
const eventLines = computed(() => caserun.events.map((event) => `[${formatTimestamp(event.at)}] ${event.stage} ${event.status}${event.payload ? ` ${JSON.stringify(event.payload)}` : ""}`));
const artifactCount = computed(() => Number(caserun.currentRun?.facts?.artifactCount ?? 0));
const jobId = computed(() => String(caserun.currentRun?.facts?.jobId ?? ""));
const aggregateHash = computed(() => caserun.aggregate?.sha256 ?? "");
const blockerText = computed(() => caserun.currentRun?.blocker ? `${caserun.currentRun.blocker.code}: ${caserun.currentRun.blocker.summary}` : "");
const fixtureMode = computed(() => String(caserun.aggregate?.mode ?? caserun.currentRun?.mode ?? caserun.cases[0]?.mode ?? "live"));

onMounted(async () => {
  await caserun.refreshCases();
  selectedCaseId.value = caserun.selectedCaseId;
  pollTimer = setInterval(() => {
    if (caserun.shouldPoll) void caserun.refreshRun();
  }, 5000);
});

onBeforeUnmount(() => {
  if (pollTimer !== null) clearInterval(pollTimer);
});

watch(() => caserun.selectedCaseId, (caseId) => {
  if (!selectedCaseId.value) selectedCaseId.value = caseId;
});

async function startRun(): Promise<void> {
  const caseId = selectedCaseId.value || caserun.selectedCaseId;
  if (!caseId) return;
  await caserun.startRun(caseId);
}
</script>

<template>
  <aside class="caserun-panel" id="caserun-panel" aria-label="CaseRun 控制面板">
    <div class="panel-header compact">
      <div>
        <p class="page-eyebrow">CaseRun</p>
        <h2>HWPOD</h2>
      </div>
      <StatusBadge :status="statusTone" :label="runStatus" />
    </div>
    <div class="caserun-controls">
      <label for="caserun-case-select">case</label>
      <select id="caserun-case-select" v-model="selectedCaseId" :disabled="caserun.loading || caserun.starting">
        <option v-for="item in caserun.cases" :key="item.caseId" :value="item.caseId">{{ item.title || item.caseId }}</option>
      </select>
      <button id="caserun-start" type="button" :disabled="!selectedCaseId || caserun.starting" @click="startRun">启动</button>
      <button id="caserun-refresh" type="button" :disabled="!caserun.currentRun?.runId" @click="caserun.refreshRun()">刷新</button>
    </div>
    <dl class="caserun-meta" id="caserun-status">
      <div><dt>run</dt><dd id="caserun-run-id">{{ caserun.currentRun?.runId || '-' }}</dd></div>
      <div><dt>stage</dt><dd>{{ caserun.currentRun?.stage || '-' }}</dd></div>
      <div><dt>mode</dt><dd>{{ fixtureMode }}</dd></div>
      <div><dt>terminal</dt><dd>{{ caserun.currentRun?.terminal ?? '-' }}</dd></div>
      <div><dt>job</dt><dd>{{ jobId || '-' }}</dd></div>
      <div><dt>artifacts</dt><dd>{{ artifactCount }}</dd></div>
    </dl>
    <section class="caserun-event-panel" aria-label="CaseRun event log">
      <header>
        <span>events</span>
        <span>{{ caserun.events.length }}</span>
      </header>
      <pre id="caserun-event-text">{{ eventLines.join('\n') || blockerText || caserun.error || '等待 CaseRun。' }}</pre>
    </section>
    <section class="caserun-aggregate" id="caserun-aggregate" aria-label="CaseRun aggregate">
      <strong id="caserun-aggregate-sha">{{ aggregateHash || 'aggregate pending' }}</strong>
      <span id="caserun-aggregate-status">{{ caserun.aggregate?.status || 'pending' }}</span>
      <small id="caserun-aggregate-run-id">{{ caserun.aggregate?.runId || '-' }}</small>
    </section>
  </aside>
</template>
