import { request } from './client'

export type RunState = 'running' | 'stopped' | 'crashed'

export interface RunProfile {
  id: string
  workspace_id: string
  slug: string
  name: string
  description: string
  command: string
  args: string[]
  env_keys: string[]
  enabled: boolean
  status: RunState
  started_at: string | null
  last_started_at: string | null
  last_exit_code: number | null
  last_error: string
  created_at: string
  updated_at: string
}

export interface RunStatus {
  status: RunState
  started_at: string | null
  last_exit_code: number | null
  last_error: string
}

export interface LogLine {
  id: number
  level: 'info' | 'error'
  text: string
  ts: string
}

export interface CreateRunProfileBody {
  slug: string
  name: string
  description?: string
  command: string
  args?: string[]
  env?: Record<string, string>
  enabled?: boolean
}

export type UpdateRunProfileBody = Partial<CreateRunProfileBody>

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

export const runsApi = {
  list: (wsID: string) => request<RunProfile[]>(`/api/v1/workspaces/${enc(wsID)}/run-profiles/`),
  create: (wsID: string, body: CreateRunProfileBody) =>
    request<RunProfile>(`/api/v1/workspaces/${enc(wsID)}/run-profiles/`, { method: 'POST', body }),
  update: (id: string, body: UpdateRunProfileBody) =>
    request<RunProfile>(`/api/v1/run-profiles/${enc(id)}`, { method: 'PATCH', body }),
  remove: (id: string) => request<void>(`/api/v1/run-profiles/${enc(id)}`, { method: 'DELETE' }),
  start: (id: string) =>
    request<RunStatus>(`/api/v1/run-profiles/${enc(id)}/start`, { method: 'POST' }),
  stop: (id: string) =>
    request<RunStatus>(`/api/v1/run-profiles/${enc(id)}/stop`, { method: 'POST' }),
  restart: (id: string) =>
    request<RunStatus>(`/api/v1/run-profiles/${enc(id)}/restart`, { method: 'POST' }),
  status: (id: string) => request<RunStatus>(`/api/v1/run-profiles/${enc(id)}/status`),
}

// openRunLogsWS 打开到日志流的原生 WebSocket。浏览器 WS 不支持自定义 header，
// 故 token 经 ?token= 传递（同 acp WS 约定）。
export function openRunLogsWS(profileID: string, since: number, token: string): WebSocket {
  const proto = window.location.protocol === 'https:' ? 'wss' : 'ws'
  const host = window.location.host
  const url =
    `${proto}://${host}/api/v1/run-profiles/${enc(profileID)}` +
    `/logs/stream?since=${since}&token=${enc(token)}`
  return new WebSocket(url)
}
