import { get, post, del } from '../request'
import type { CompareTask, CompareModelRef } from '@/types'

/** 推理/对比任务列表 */
export const getCompareList = () => get<CompareTask[]>('/model-compare')

/** 任务详情 */
export const getCompare = (id: string | number) => get<CompareTask>(`/model-compare/${id}`)

/** 创建任务 */
export const createCompare = (data: Partial<CompareTask>) =>
  post<{ id: string | number }>('/model-compare', data)

/** 删除任务 */
export const deleteCompare = (id: string | number) => del(`/model-compare/${id}`)

/** 更新任务加载状态 */
export const updateLoadStatus = (id: string | number, load_status: any) =>
  post(`/model-compare/${id}/load-status`, { load_status })

/** 查询任务加载状态 */
export const getLoadStatus = (id: string | number) =>
  get<{ all_ready: boolean; loaded_models: any[] }>(`/model-compare/${id}/load-status`)

/** 停止所有旧模型服务 */
export const stopAllModels = () => post('/model-compare/all/stop-all')

/** 启动单个模型服务 */
export const startModel = (id: string | number, data: Partial<CompareModelRef>) =>
  post<{ pid: number; port: number }>(`/model-compare/${id}/start-model`, data)

/** 按 PID 停止模型进程 */
export const stopModelByPid = (pid: number) =>
  post('/model-compare/stop-by-pid', { pid })

/** 加载任务 */
export const loadCompare = (id: string | number) => post(`/model-compare/${id}/load`)

/** 卸载任务 */
export const unloadCompare = (id: string | number) => post(`/model-compare/${id}/unload`)

/** 流式对话（mock 模式下返回非流式响应，调用方需兼容） */
export const streamChat = async (data: any): Promise<any> => {
  // Mock 环境：返回非流式响应对象，调用方检测 content-type 决定如何处理
  const resp = await post<{ response: string }>('/model-compare/stream-chat', data)
  return {
    ok: true,
    body: {
      getReader: () => {
        // 模拟流式读取：把整个响应切成小块逐个返回
        const text = resp?.response || ''
        const encoder = new TextEncoder()
        const chunks = [text.slice(0, text.length / 3), text.slice(text.length / 3, 2 * text.length / 3), text.slice(2 * text.length / 3)]
        let i = 0
        return {
          read: async () => {
            if (i >= chunks.length) return { done: true, value: undefined }
            const value = encoder.encode(chunks[i++])
            return { done: false, value }
          },
        }
      },
    },
  }
}

/** 非流式对话（按端口代理） */
export const chatWithPort = (data: any) => post('/model-compare/chat-with-port', data)

/** 批量对话（API 类型模型） */
export const batchChat = (data: any) => post('/model-chat/batch', data)

/** 本地 transformers 模型对话 */
export const localChat = (data: any) => post('/model-chat/local/chat', data)

/** 预加载本地模型 */
export const preloadLocalModel = (data: any) => post('/model-chat/local/preload', data)

/** 预加载已训练模型 */
export const preloadTrainedModel = (data: any) => post('/model-chat/trained/preload', data)
