/** Terminal API client */

const API_BASE = '/api/v1'

export interface ICommandRecord {
  command: string
  exit_code: number
  output: string
  cwd: string
  timestamp: number
  duration_ms: number
}

export interface ITerminalSession {
  session_id: string
  cwd: string
  created_at: number
}

export interface IExecuteResponse {
  session_id: string
  command: string
  exit_code: number
  output: string
  cwd: string
  duration_ms: number
}

async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
  const url = `${API_BASE}${path}`
  const headers: HeadersInit = {
    'Content-Type': 'application/json',
    ...options.headers,
  }

  const response = await fetch(url, { ...options, headers })

  if (!response.ok) {
    const error = { status: response.status, message: response.statusText }
    try {
      const body = await response.json()
      error.message = body.detail ?? body.message ?? error.message
    } catch {
      // use status text
    }
    throw error
  }

  return response.json() as Promise<T>
}

/** Create a terminal WebSocket URL */
export function createTerminalWsUrl(sessionId?: string): string {
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  const host = window.location.host
  const base = `${protocol}//${host}${API_BASE}/terminal/ws`
  return sessionId ? `${base}?session_id=${sessionId}` : base
}

/** Execute a command via REST API */
export async function executeCommand(
  command: string,
  sessionId?: string
): Promise<IExecuteResponse> {
  return request<IExecuteResponse>('/terminal/execute', {
    method: 'POST',
    body: JSON.stringify({ command, session_id: sessionId }),
  })
}

/** List terminal sessions */
export async function listSessions(): Promise<{ sessions: ITerminalSession[] }> {
  return request<{ sessions: ITerminalSession[] }>('/terminal/sessions')
}

/** Get command history for a session */
export async function getCommandHistory(
  sessionId: string
): Promise<{ history: ICommandRecord[] }> {
  return request<{ history: ICommandRecord[] }>(`/terminal/sessions/${sessionId}/history`)
}
