import { request } from './client'
import type { Phase } from './projects'

export type OrchestratorRunStatus =
  | 'pending'
  | 'running'
  | 'paused'
  | 'succeeded'
  | 'failed'
  | 'canceled'

export interface OrchestratorRun {
  id: string
  project_id: string
  requirement_id: string
  workspace_id: string
  owner_id: string
  status: OrchestratorRunStatus
  current_phase: Phase
  last_error?: string
  created_at: string
  updated_at: string
  ended_at?: string | null
}

export interface StartOrchestratorRunBody {
  project_slug: string
  requirement_number: number
  start_phase?: Phase
  phase_agent_kinds?: Record<string, string>
  max_attempts_per_phase?: number
  max_depth?: number
  fan_out_limit?: number
}

const enc = (v: string) => encodeURIComponent(v)

export const orchestratorApi = {
  listRuns: (
    params: { project_id?: string; requirement_id?: string; status?: OrchestratorRunStatus } = {},
  ) => {
    const q = new URLSearchParams()
    if (params.project_id) q.set('project_id', params.project_id)
    if (params.requirement_id) q.set('requirement_id', params.requirement_id)
    if (params.status) q.set('status', params.status)
    const qs = q.toString()
    return request<OrchestratorRun[]>(`/api/v1/orchestrator/runs/${qs ? '?' + qs : ''}`)
  },
  startRun: (body: StartOrchestratorRunBody) =>
    request<OrchestratorRun>('/api/v1/orchestrator/runs/', { method: 'POST', body }),
  pauseRun: (id: string) =>
    request<OrchestratorRun>(`/api/v1/orchestrator/runs/${enc(id)}/pause`, { method: 'POST' }),
  resumeRun: (id: string) =>
    request<OrchestratorRun>(`/api/v1/orchestrator/runs/${enc(id)}/resume`, { method: 'POST' }),
  cancelRun: (id: string) =>
    request<OrchestratorRun>(`/api/v1/orchestrator/runs/${enc(id)}/cancel`, { method: 'POST' }),
}
