import { apiClient } from "./client";

export interface AgentStepDTO {
  id: number;
  stepKey: string;
  stepName: string;
  agentType: "DECISION" | "EXECUTOR" | "SUPERVISION";
  status: "PENDING" | "RUNNING" | "DONE" | "FAILED" | "SKIPPED";
  score?: "A" | "B" | "C" | "D";
  scoreDetail?: string;
  output?: string;
  durationMs?: number;
  startedAt?: string;
  doneAt?: string;
  seq: number;
}

export interface AgentRunDTO {
  id: number;
  projectId: number;
  goal: string;
  status: "PENDING" | "RUNNING" | "PAUSED" | "DONE" | "FAILED";
  createdAt: string;
  steps: AgentStepDTO[];
}

export interface AgentStartRequest {
  goal: string;
  runIntent?: "auto" | "script_understanding" | "continue_existing" | string;
  forceRegenerate?: boolean;
  selectedSteps?: string[];
  contextOptions?: {
    useScriptAsset?: boolean;
    useExistingOutline?: boolean;
    useExistingEpisodes?: boolean;
    useExistingAssets?: boolean;
    useExistingStoryboards?: boolean;
  };
  idempotencyKey?: string;
}

export const agentApi = {
  startRun: (projectId: string, request: string | AgentStartRequest) =>
    apiClient
      .post<{ data: AgentRunDTO }>(
        `/agent/projects/${projectId}/runs`,
        typeof request === "string" ? { goal: request } : request,
      )
      .then((r) => r.data.data),

  getLatestRun: (projectId: string) =>
    apiClient
      .get<{ data: AgentRunDTO | null }>(`/agent/projects/${projectId}/runs/latest`)
      .then((r) => r.data.data ?? null),

  getRun: (runId: number) =>
    apiClient
      .get<{ data: AgentRunDTO }>(`/agent/runs/${runId}`)
      .then((r) => r.data.data),

  pauseRun: (runId: number) =>
    apiClient.post(`/agent/runs/${runId}/pause`),

  resumeRun: (runId: number) =>
    apiClient.post(`/agent/runs/${runId}/resume`),
};
