import { computed, ref } from "vue";
import { defineStore } from "pinia";
import { caserunAPI } from "@/api";
import type { CaseRunAggregateResponse, CaseRunCaseSummary, CaseRunEvent, CaseRunListItem, CaseRunRunResponse } from "@/types";

export const useCaseRunStore = defineStore("caserun", () => {
  const cases = ref<CaseRunCaseSummary[]>([]);
  const runs = ref<CaseRunListItem[]>([]);
  const nextRunsCursor = ref<string | null>(null);
  const currentRun = ref<CaseRunRunResponse | null>(null);
  const events = ref<CaseRunEvent[]>([]);
  const aggregate = ref<CaseRunAggregateResponse | null>(null);
  const loading = ref(false);
  const starting = ref(false);
  const runsLoading = ref(false);
  const error = ref<string | null>(null);
  const runsError = ref<string | null>(null);
  const selectedCaseId = computed(() => currentRun.value?.caseId ?? cases.value[0]?.caseId ?? "");
  const shouldPoll = computed(() => Boolean(currentRun.value?.runId && currentRun.value.terminal === false));

  async function refreshCases(): Promise<void> {
    loading.value = true;
    error.value = null;
    const result = await caserunAPI.cases();
    cases.value = result.data?.cases ?? [];
    error.value = result.ok ? null : result.error ?? "无法读取 CaseRun 用例";
    loading.value = false;
  }

  async function refreshRuns(options: { append?: boolean } = {}): Promise<void> {
    if (runsLoading.value) return;
    runsLoading.value = true;
    runsError.value = null;
    const cursor = options.append ? nextRunsCursor.value ?? undefined : undefined;
    const result = await caserunAPI.runs({ limit: 30, cursor });
    if (result.ok && result.data) {
      const incoming = result.data.runs ?? [];
      runs.value = options.append ? [...runs.value, ...incoming.filter((item) => !runs.value.some((existing) => existing.runId === item.runId))] : incoming;
      nextRunsCursor.value = result.data.nextCursor ?? null;
    } else {
      runsError.value = result.error ?? "无法读取最近运行";
    }
    runsLoading.value = false;
  }

  async function startRun(caseId: string): Promise<CaseRunRunResponse | null> {
    starting.value = true;
    error.value = null;
    events.value = [];
    aggregate.value = null;
    const result = await caserunAPI.startRun(caseId);
    starting.value = false;
    if (!result.ok || !result.data) {
      error.value = result.error ?? "CaseRun 启动失败";
      return null;
    }
    currentRun.value = result.data;
    await refreshRun(result.data.runId ?? "");
    await refreshRuns();
    return result.data;
  }

  async function refreshRun(runId = currentRun.value?.runId ?? ""): Promise<boolean> {
    if (!runId) return false;
    const result = await caserunAPI.run(runId);
    if (!result.ok || !result.data) {
      error.value = result.error ?? "无法读取 CaseRun 运行";
      if (currentRun.value?.runId !== runId) {
        currentRun.value = null;
        events.value = [];
        aggregate.value = null;
      }
      return false;
    }
    error.value = null;
    currentRun.value = result.data;
    await Promise.all([refreshEvents(runId), refreshAggregate(runId)]);
    return true;
  }

  async function refreshEvents(runId = currentRun.value?.runId ?? ""): Promise<void> {
    if (!runId) return;
    const result = await caserunAPI.events(runId);
    if (result.ok && result.data?.runId === runId) events.value = result.data.events ?? [];
  }

  async function refreshAggregate(runId = currentRun.value?.runId ?? ""): Promise<void> {
    if (!runId) return;
    const result = await caserunAPI.aggregate(runId);
    if (result.ok && result.data?.runId === runId) aggregate.value = result.data;
  }

  return {
    cases, runs, nextRunsCursor, currentRun, events, aggregate,
    loading, runsLoading, starting, error, runsError,
    selectedCaseId, shouldPoll,
    refreshCases, refreshRuns, startRun, refreshRun, refreshEvents, refreshAggregate
  };
});
