import type { AiModel } from "./types"
import { apiClient } from "./client"
import type { PaginatedResponse, PaginationParams } from "./client"

// 将后端 Bot 数据映射到前端 AiModel 类型
// 后端 Bot 只有 id, name, description；其他字段用默认值
function mapBackendBot(b: any): AiModel {
  return {
    id: String(b.id),
    name: b.name,
    version: "1.0.0",
    description: b.description || "",
    status: "活跃",
    parameters: undefined,
    accuracy: undefined,
    trainingData: undefined,
    createdAt: undefined,
    updatedAt: undefined,
  }
}

// 获取AI模型(Bot)列表
export const getAiModels = async (params?: PaginationParams): Promise<PaginatedResponse<AiModel>> => {
  const page = params?.page || 1
  const pageSize = params?.pageSize || 10
  const searchParam = params?.search ? `&search=${encodeURIComponent(params.search)}` : ""

  const response = await apiClient.get(
    `/ai/bots/?page=${page}&page_size=${pageSize}${searchParam}`
  )

  const data = response.data?.data || response.data
  const results: any[] = data.results || (Array.isArray(data) ? data : [data])
  const total = data.count || results.length

  return {
    items: results.map(mapBackendBot),
    total,
    page,
    pageSize,
    totalPages: Math.ceil(total / pageSize),
  }
}

// 获取单个AI模型
export const getAiModel = async (id: string): Promise<AiModel> => {
  const response = await apiClient.get(`/ai/bots/${id}/`)
  const data = response.data?.data || response.data
  return mapBackendBot(data)
}

// 创建AI模型（需要管理员权限）
export const createAiModel = async (modelData: Partial<AiModel>): Promise<AiModel> => {
  const payload = {
    name: modelData.name,
    description: modelData.description || "",
  }

  const response = await apiClient.post(`/ai/bots/`, payload)
  const data = response.data?.data || response.data
  return mapBackendBot(data)
}

// 更新AI模型（需要管理员权限）
export const updateAiModel = async (id: string, modelData: Partial<AiModel>): Promise<AiModel> => {
  const payload: any = {}
  if (modelData.name !== undefined) payload.name = modelData.name
  if (modelData.description !== undefined) payload.description = modelData.description

  const response = await apiClient.patch(`/ai/bots/${id}/`, payload)
  const data = response.data?.data || response.data
  return mapBackendBot(data)
}

// 删除AI模型（需要管理员权限）
export const deleteAiModel = async (id: string): Promise<boolean> => {
  await apiClient.delete(`/ai/bots/${id}/`)
  return true
}

// 发布AI模型（Bot没有发布概念，这里直接返回当前数据）
export const publishAiModel = async (id: string): Promise<AiModel> => {
  return getAiModel(id)
}
