const BASE = '/api'

async function request<T>(path: string, opts?: RequestInit): Promise<T> {
  const res = await fetch(`${BASE}${path}`, {
    headers: { 'Content-Type': 'application/json' },
    ...opts,
  })
  if (!res.ok) {
    const err = await res.json().catch(() => ({ error: res.statusText }))
    throw new Error(err.error || res.statusText)
  }
  return res.json()
}

export interface Plan {
  id: number
  title: string
  description: string
  team: string
  priority: string
  status: string
  created_at: string
  updated_at: string
  approved_at?: string
  started_at?: string
  completed_at?: string
}

export interface Task {
  id: number
  plan_id: number
  title: string
  description?: string
  task_type: string
  status: string
  assigned_agent?: string
  progress_note?: string
  sort_order: number
  created_at?: string
  updated_at?: string
  started_at?: string
  completed_at?: string
}

export interface Agent {
  id: string
  name: string
  team: string
  role: string
  model_provider: string
  model_id: string
  gpu_default?: string
  status: string
  current_task_id?: number
  last_seen_at?: string
}

export interface QueueItem {
  id: number
  plan_id?: number
  task_id?: number
  status: string
  verification_notes?: string
  director_notes?: string
  submitted_at: string
  reviewed_at?: string
  plan_title: string
  task_title: string
}

export interface PendingQuestion {
  id: number
  plan_id?: number
  task_id?: number
  from_role: string
  from_id: string
  question: string
  context?: string
  priority: string
  status: string
  answer?: string
  created_at: string
  answered_at?: string
  plan_title?: string
  task_title?: string
}

export interface Message {
  id: number
  plan_id: number
  task_id?: number
  reply_to_id?: number
  from_role: string
  from_id: string
  message: string
  message_type: string
  created_at: string
}

export interface ClaudeMode {
  mode: 'api' | 'proxy' | 'unknown'
  output: string
}

export const api = {
  system: {
    getClaudeMode: () => request<ClaudeMode>('/system/claude-mode'),
    setClaudeMode: (mode: 'api' | 'proxy') =>
      request<ClaudeMode>('/system/claude-mode', {
        method: 'POST',
        body: JSON.stringify({ mode }),
      }),
  },
  plans: {
    list: () => request<Plan[]>('/plans'),
    get: (id: number) => request<Plan>(`/plans/${id}`),
    create: (data: Partial<Plan>) => request<Plan>('/plans', { method: 'POST', body: JSON.stringify(data) }),
    update: (id: number, data: Partial<Plan>) => request<Plan>(`/plans/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  },
  tasks: {
    list: (planId: number) => request<Task[]>(`/plans/${planId}/tasks`),
    create: (planId: number, data: Partial<Task>) => request<Task>(`/plans/${planId}/tasks`, { method: 'POST', body: JSON.stringify(data) }),
    update: (id: number, data: Partial<Task>) => request<Task>(`/tasks/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  },
  agents: {
    list: () => request<Agent[]>('/agents'),
  },
  queue: {
    list: (status?: string) => request<QueueItem[]>(`/queue${status ? `?status=${status}` : ''}`),
    update: (id: number, data: { status: string; director_notes?: string }) => request<QueueItem>(`/queue/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  },
  questions: {
    list: (status?: string) => request<PendingQuestion[]>(`/questions${status ? `?status=${status}` : ''}`),
    answer: (id: number, answer: string) => request<{ id: number; status: string }>(`/questions/${id}`, {
      method: 'PATCH',
      body: JSON.stringify({ answer }),
    }),
  },
  messages: {
    list: (planId: number) => request<Message[]>(`/plans/${planId}/messages`),
    create: (planId: number, data: Partial<Message>) => request<Message>(`/plans/${planId}/messages`, { method: 'POST', body: JSON.stringify(data) }),
    update: (id: number, message: string) => request<{ id: number; message: string }>(`/messages/${id}`, { method: 'PATCH', body: JSON.stringify({ message }) }),
  },
}
