import request from '../utils/request'

// ============================== 分类管理 ==============================

export function getKbCategories(parentId) {
  const params = parentId !== undefined && parentId !== null ? { parentId } : {}
  return request.get('/kb/categories', { params })
}

export function getKbCategory(id) {
  return request.get(`/kb/categories/${id}`)
}

export function createKbCategory(data) {
  return request.post('/kb/categories', data)
}

export function updateKbCategory(id, data) {
  return request.put(`/kb/categories/${id}`, data)
}

export function deleteKbCategory(id) {
  return request.delete(`/kb/categories/${id}`)
}

export function getKbStatus() {
  return request.get('/kb/categories/_status')
}

// ============================== 文档管理 ==============================

/**
 * 上传文档（multipart/form-data）
 * @param {File} file
 * @param {number|null} categoryId
 * @param {(progress: number) => void} onProgress 上传进度回调（0-100）
 */
export function uploadKbDocument(file, categoryId, onProgress) {
  const formData = new FormData()
  formData.append('file', file)
  if (categoryId !== undefined && categoryId !== null) {
    formData.append('categoryId', categoryId)
  }
  return request.post('/kb/documents/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 600000, // 10 分钟（大文件）
    onUploadProgress: (e) => {
      if (onProgress && e.total) {
        onProgress(Math.round((e.loaded / e.total) * 100))
      }
    }
  })
}

export function getKbDocuments(params) {
  return request.get('/kb/documents', { params })
}

export function getKbDocument(id) {
  return request.get(`/kb/documents/${id}`)
}

export function getKbDocumentChunks(id) {
  return request.get(`/kb/documents/${id}/chunks`)
}

export function revectorizeKbDocument(id) {
  return request.post(`/kb/documents/${id}/revectorize`)
}

export function vectorizeKbDocument(id) {
  return request.post(`/kb/documents/${id}/vectorize`)
}

export function vectorizeKbChunk(chunkId) {
  return request.post(`/kb/documents/chunks/${chunkId}/vectorize`)
}

export function moveKbDocument(id, categoryId) {
  return request.post(`/kb/documents/${id}/move`, { categoryId })
}

export function deleteKbDocument(id) {
  return request.delete(`/kb/documents/${id}`)
}

export function getKbDependencies() {
  return request.get('/kb/documents/_dependencies')
}

// ============================== 向量检索 ==============================

/**
 * 向量检索（语义召回）
 * @param {Object} params { query, topK?, similarityThreshold?, categoryId? }
 * @returns {Promise} 命中分块列表
 */
export function searchKb(params) {
  return request.post('/kb/search', {
    query: params.query,
    topK: params.topK ?? 5,
    similarityThreshold: params.similarityThreshold ?? 0.0,
    categoryId: params.categoryId ?? null
  })
}
