import type {
  WorkflowProgressEvent,
  WorkflowProgressStatus,
} from "./orchestrator";

export interface WorkflowProgressStep {
  label: string;
  status: WorkflowProgressStatus;
  started_at: string;
  completed_at?: string;
  duration_ms?: number;
}

export interface WorkflowProgressSnapshot {
  job_id: string;
  current_step: string | null;
  status: "idle" | "running" | "completed" | "failed";
  started_at: string | null;
  updated_at: string | null;
  steps: WorkflowProgressStep[];
}

const progressByJob = new Map<string, WorkflowProgressSnapshot>();

export function startWorkflowProgress(jobId: string) {
  const now = new Date().toISOString();
  const snapshot: WorkflowProgressSnapshot = {
    job_id: jobId,
    current_step: null,
    status: "running",
    started_at: now,
    updated_at: now,
    steps: [],
  };
  progressByJob.set(jobId, snapshot);
  return snapshot;
}

export function recordWorkflowProgress(
  jobId: string,
  event: WorkflowProgressEvent,
) {
  const now = new Date().toISOString();
  const snapshot = progressByJob.get(jobId) ?? startWorkflowProgress(jobId);
  const existing = snapshot.steps.find((step) => step.label === event.label);

  if (existing) {
    existing.status = event.status;
    existing.duration_ms = event.duration_ms ?? existing.duration_ms;
    if (event.status !== "running") {
      existing.completed_at = now;
    }
  } else {
    snapshot.steps.push({
      label: event.label,
      status: event.status,
      started_at: now,
      completed_at: event.status === "running" ? undefined : now,
      duration_ms: event.duration_ms,
    });
  }

  snapshot.current_step =
    event.status === "running" ? event.label : snapshot.current_step;
  if (event.status === "failed") {
    snapshot.status = "failed";
  } else if (event.label === "整理结果" && event.status === "completed") {
    snapshot.status = "completed";
    snapshot.current_step = null;
  } else {
    snapshot.status = "running";
  }
  snapshot.updated_at = now;
  return snapshot;
}

export function getWorkflowProgress(jobId: string) {
  return (
    progressByJob.get(jobId) ?? {
      job_id: jobId,
      current_step: null,
      status: "idle",
      started_at: null,
      updated_at: null,
      steps: [],
    }
  );
}
