import type {
  IChatRequest,
  IChatResponse,
  ICapabilitiesResponse,
  IConversation,
  ITaskRecord,
  TaskStatus,
  IExpertsResponse,
  IUploadResponse,
} from './types'
import { BaseApiClient } from './base'

const API_BASE = '/api/v1/portal'

export interface IModelInfo {
  id: string
  provider: string
  model: string
  max_tokens: number | null
  cost_per_1k_input: number | null
  cost_per_1k_output: number | null
}

export interface IModelsResponse {
  models: IModelInfo[]
  aliases: Record<string, string>
  default: string | null
}

class ApiClient extends BaseApiClient {
  constructor(baseUrl: string = API_BASE) {
    super(baseUrl)
  }

  /** Send a chat message via REST API */
  async chat(request: IChatRequest): Promise<IChatResponse> {
    return this.request<IChatResponse>('/chat', {
      method: 'POST',
      body: JSON.stringify(request),
    })
  }

  /** Get all available capabilities */
  async getCapabilities(): Promise<ICapabilitiesResponse> {
    return this.request<ICapabilitiesResponse>('/capabilities')
  }

  /** Get conversation list */
  async getConversations(): Promise<IConversation[]> {
    return this.request<IConversation[]>('/conversations')
  }

  /** Get a single conversation by ID */
  async getConversation(id: string): Promise<IConversation> {
    return this.request<IConversation>(`/conversations/${id}`)
  }

  /** Delete a conversation and all its messages */
  async deleteConversation(id: string): Promise<void> {
    await this.request(`/conversations/${id}`, { method: 'DELETE' })
  }

  /** Get a task by ID (uses /api/v1/tasks prefix) */
  async getTask(taskId: string): Promise<ITaskRecord> {
    return this.request<ITaskRecord>(`/api/v1/tasks/${taskId}`)
  }

  /** List tasks, optionally filtered by status (uses /api/v1/tasks prefix) */
  async listTasks(status?: TaskStatus, limit: number = 100): Promise<ITaskRecord[]> {
    const params = new URLSearchParams()
    if (status) params.set('status', status)
    params.set('limit', String(limit))
    return this.request<ITaskRecord[]>(`/api/v1/tasks?${params.toString()}`)
  }

  /** Create a WebSocket connection for real-time chat */
  createWebSocket(): WebSocket {
    return super.createWebSocket('/ws')
  }

  /** List available expert templates for @board mode (uses /api/v1 prefix) */
  async getExperts(): Promise<IExpertsResponse> {
    return this.request<IExpertsResponse>('/api/v1/experts')
  }

  /** Upload a file to be referenced in chat messages */
  async uploadFile(file: File): Promise<IUploadResponse> {
    const formData = new FormData()
    formData.append('file', file)
    return this.request<IUploadResponse>('/api/v1/chat/upload', {
      method: 'POST',
      body: formData,
    })
  }

  /** List available LLM models (uses /api/v1 prefix) */
  async listModels(): Promise<IModelsResponse> {
    return this.request<IModelsResponse>('/api/v1/llm/models')
  }
}

export const apiClient = new ApiClient()
export { ApiClient }
