import axios from 'axios'
import { handleAuthError } from './auth.js'

const API_BASE_URL = '/api'

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json'
  }
})

apiClient.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => Promise.reject(error)
)

apiClient.interceptors.response.use(
  response => response,
  error => {
    const status = error.response?.status
    if (status === 401 || status === 403) {
      handleAuthError()
      return Promise.reject(error)
    }
    if (status === 404) {
      const err = new Error('接口不存在，请确认后端已部署最新版本')
      err.code = 'NOT_FOUND'
      err.status = status
      return Promise.reject(err)
    }
    if (status === 500) {
      const serverMsg = error.response?.data?.message || error.response?.data?.msg || ''
      let detailMsg = '服务暂不可用'
      if (serverMsg.includes('Connection refused') || serverMsg.includes('连接被拒绝')) {
        detailMsg = 'RAG服务（端口5001）未启动，请先启动RAG服务'
      } else if (serverMsg.includes('timeout') || serverMsg.includes('超时')) {
        detailMsg = '服务响应超时，请稍后重试'
      } else if (serverMsg.includes('AI生成题目失败')) {
        detailMsg = serverMsg
      } else if (serverMsg) {
        detailMsg = `服务错误: ${serverMsg}`
      } else {
        detailMsg = '服务暂不可用，请确认服务是否已启动'
      }
      const err = new Error(detailMsg)
      err.code = 'RAG_UNAVAILABLE'
      err.status = status
      return Promise.reject(err)
    }
    if (!error.response) {
      const reqUrl = error.config?.url || error.config?.baseURL + (error.config?.url || '')
      const isTimeout = error.code === 'ECONNABORTED'
      const isAborted = error.message?.includes('aborted') || error.code?.includes('ABORTED')
      let detail = '网络连接失败，请检查网络设置'
      if (isAborted) {
        detail = `请求被中断（ERR_ABORTED），接口: ${reqUrl}，可能原因: 服务端超时/CORS/接口未部署`
      } else if (isTimeout) {
        detail = `请求超时（${error.config?.timeout || '默认'}ms）: ${reqUrl}`
      }
      console.error('[ragAPI] 网络错误:', { code: error.code, message: error.message, url: reqUrl, timeout: error.config?.timeout })
      const err = new Error(detail)
      err.code = 'NETWORK_ERROR'
      err.originalCode = error.code
      err.requestUrl = reqUrl
      return Promise.reject(err)
    }
    return Promise.reject(error)
  }
)

function handleRagResponse(response) {
  const data = response.data

  if (!data) {
    throw new Error('服务器返回空数据')
  }

  if (data.code === 200 && data.data) {
    const ragData = data.data
    const statusCode = ragData.status_code || ragData.statusCode || 0

    if (statusCode >= 2000 && statusCode < 3000) {
      console.log(`✅ RAG操作成功 (status_code: ${statusCode})`)
      return ragData
    }

    if (statusCode >= 4000 && statusCode < 5000) {
      const errorMsg = ragData.message || ragData.error || '请求参数错误'
      console.error(`❌ RAG参数错误 (status_code: ${statusCode}):`, errorMsg)
      throw new Error(errorMsg)
    }

    if (statusCode >= 5000 && statusCode < 6000) {
      const errorMsg = ragData.message || ragData.error || 'RAG服务内部错误'
      console.error(`❌ RAG服务错误 (status_code: ${statusCode}):`, errorMsg)
      throw new Error(errorMsg)
    }

    if (ragData.success === false) {
      let errorMsg = ragData.error || ragData.message || '操作失败'

      // 智能提取Connection refused等关键错误
      if (errorMsg.includes('Connection refused') || errorMsg.includes('连接被拒绝')) {
        errorMsg = 'RAG知识库服务未启动（端口5001），请先启动RAG服务后再试'
      } else if (errorMsg.includes('I/O error') || errorMsg.includes('I/O 错误')) {
        errorMsg = '无法连接到RAG服务，请确认服务是否已启动'
      } else if (errorMsg.includes('timeout') || errorMsg.includes('超时')) {
        errorMsg = 'RAG服务响应超时，请稍后重试或检查服务状态'
      }

      console.error('❌ RAG操作失败:', errorMsg)
      throw new Error(errorMsg)
    }

    return ragData
  }

  if (data.code !== 200 && data.code !== undefined) {
    let errorMsg = data.message || data.msg || `请求失败 (code: ${data.code})`

    // 智能识别常见连接问题
    if (errorMsg.includes('Connection refused') || errorMsg.includes('连接被拒绝')) {
      errorMsg = 'RAG知识库服务未启动（端口5001），请先启动RAG服务'
    } else if (errorMsg.includes('I/O error')) {
      errorMsg = '无法连接到RAG服务，请确认服务是否正常运行'
    } else if (data.code === 500) {
      errorMsg = errorMsg.includes('获取向量库列表失败')
        ? 'RAG服务暂不可用，请确认RAG服务（端口5001）已启动'
        : `服务器内部错误: ${errorMsg}`
    }

    console.error(`❌ API错误 (code: ${data.code}):`, errorMsg)
    throw new Error(errorMsg)
  }

  return data.data || data
}

export const ragAPI = {
  healthCheck: () => {
    return apiClient.get('/rag/health').then(handleRagResponse)
  },

  getKnowledgeBasePaths: (params = {}) => {
    return apiClient.get('/kb-path/page', { params }).then(handleRagResponse)
  },

  getKnowledgeBasePathById: (id) => {
    return apiClient.get(`/kb-path/${id}`).then(handleRagResponse)
  },

  createKnowledgeBasePath: (data) => {
    return apiClient.post('/kb-path', data).then(handleRagResponse)
  },

  updateKnowledgeBasePath: (id, data) => {
    return apiClient.put(`/kb-path/${id}`, data).then(handleRagResponse)
  },

  deleteKnowledgeBasePath: (id) => {
    return apiClient.delete(`/kb-path/${id}`).then(handleRagResponse)
  },

  batchDeleteKnowledgeBasePaths: (ids) => {
    return apiClient.delete('/kb-path/batch', { data: ids }).then(handleRagResponse)
  },

  getAccessibleKnowledgeBases: () => {
    return apiClient.get('/kb-path/accessible').then(handleRagResponse)
  },

  getCollections: () => {
    return apiClient.get('/collection').then(handleRagResponse)
  },

  createCollection: (data) => {
    return apiClient.post('/collection', null, { params: data }).then(handleRagResponse)
  },

  updateCollection: (name, data) => {
    return apiClient.put(`/collection/${name}`, null, { params: data }).then(handleRagResponse)
  },

  deleteCollection: (name) => {
    return apiClient.delete(`/collection/${name}`).then(handleRagResponse)
  },

  getCollectionChunks: (name, params = {}) => {
    return apiClient.get(`/collection/${name}/chunks`, { params }).then(handleRagResponse)
  },

  deprecateDocument: (kbName, filename, reason) => {
    const params = {}
    if (reason) params.reason = reason
    const url = `/collection/${kbName}/documents/${encodeURIComponent(filename)}/deprecate`
    console.log('[ragAPI] 废止文档 - URL:', url)
    console.log('[ragAPI] 废止文档 - 参数:', params)
    return apiClient.post(url, null, { params }).then(handleRagResponse)
  },

  restoreDocument: (kbName, filename) => {
    const url = `/collection/${kbName}/documents/${encodeURIComponent(filename)}/restore`
    console.log('[ragAPI] 恢复文档 - URL:', url)
    return apiClient.post(url).then(handleRagResponse)
  },

  getDocumentVersions: (kbName, filename, limit = 10) => {
    const url = `/collection/${kbName}/documents/${encodeURIComponent(filename)}/versions`
    console.log('[ragAPI] 获取版本 - URL:', url)
    console.log('[ragAPI] 获取版本 - limit:', limit)
    return apiClient.get(url, { params: { limit } }).then(handleRagResponse)
  },

  // ========== 智能向量化（自动识别知识库） ==========
  // 文档: POST /collection/vectorize/smart?fileId=xxx — 自动根据文件部门ID选择向量库

  /** 单文件智能向量化（异步提交，立即返回任务状态） */
  smartVectorizeFile: (fileId) => {
    if (fileId === null || fileId === undefined || fileId === '') {
      const err = new Error('文件ID不能为空')
      err.code = 'INVALID_PARAM'
      throw err
    }
    const numId = Number(fileId)
    if (isNaN(numId) || numId <= 0) {
      const err = new Error('文件ID必须是有效的正整数: ' + fileId)
      err.code = 'INVALID_PARAM'
      throw err
    }
    console.log('[ragAPI] 智能向量化请求: fileId=', numId)
    return apiClient.post('/collection/vectorize/smart', null, {
      params: { fileId: numId },
      timeout: 30000
    }).then(handleRagResponse).catch(err => {
      if (err.code === 'ECONNABORTED' || err.originalCode === 'ECONNABORTED') {
        console.log('[ragAPI] 智能向量化任务已提交:', { fileId: numId })
        return { submitted: true, fileId: numId, message: '智能向量化任务已提交，正在后台处理', status: 'VECTORIZING', collection: '' }
      }
      console.error('[ragAPI] 智能向量化失败:', { fileId: numId, code: err.code, message: err.message, status: err.status })
      throw err
    })
  },

  /** 批量智能向量化（异步提交，每个文件自动匹配对应部门向量库） */
  smartVectorizeBatch: (fileIds) => {
    const idsStr = Array.isArray(fileIds) ? fileIds.join(',') : String(fileIds || '')
    if (!idsStr) throw new Error('文件ID列表不能为空')
    return apiClient.post('/collection/vectorize/batch/smart', null, {
      params: { fileIds: idsStr },
      timeout: 60000
    }).then(handleRagResponse)
  },

  // ========== 传统向量化（需手动指定知识库） ==========

  vectorizeFile: (collectionName, fileId) => {
    return apiClient.post(`/collection/${encodeURIComponent(collectionName)}/vectorize`, null, {
      params: { fileId },
      timeout: 120000
    }).then(handleRagResponse)
  },

  submitVectorizeTask: (collectionName, fileId) => {
    return apiClient.post(`/collection/${encodeURIComponent(collectionName)}/vectorize`, null, {
      params: { fileId },
      timeout: 30000
    }).then(handleRagResponse).catch(err => {
      if (err.code === 'ECONNABORTED' || err.originalCode === 'ECONNABORTED') {
        console.log('[ragAPI] 向量化任务已提交（等待服务端处理中）:', { collectionName, fileId })
        return { submitted: true, collectionName, fileId, message: '任务已提交，正在后台处理', status: 'VECTORIZING' }
      }
      throw err
    })
  },

  getFileVectorizeStatus: (fileId) => {
    return apiClient.get(`/file/${fileId}`).then(response => {
      const data = response.data
      if (data?.code === 200 && data?.data) {
        return {
          processStatus: data.data.processStatus || data.data.process_status || 'PENDING',
          examStatus: data.data.examStatus || data.data.exam_status || 'UNGENERATED',
          processMessage: data.data.processMessage || data.data.process_message || ''
        }
      }
      throw new Error(data?.message || '获取文件状态失败')
    })
  },

  vectorizeBatch: (collectionName, fileIds) => {
    return apiClient.post(`/collection/${encodeURIComponent(collectionName)}/vectorize/batch`, null, {
      params: { fileIds: Array.isArray(fileIds) ? fileIds.join(',') : fileIds },
      timeout: 300000
    }).then(handleRagResponse)
  },

  uploadDocument: (file, collection) => {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('collection', collection)
    return apiClient.post('/documents/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      timeout: 120000
    }).then(handleRagResponse)
  },

  batchUploadDocuments: (files, collection) => {
    const formData = new FormData()
    files.forEach(f => formData.append('files', f))
    formData.append('collection', collection)
    return apiClient.post('/documents/batch-upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      timeout: 300000
    }).then(handleRagResponse)
  },

  getDocumentList: (collection) => {
    return apiClient.get(`/collection/${encodeURIComponent(collection)}/documents`).then(handleRagResponse)
  },

  deleteDocument: (collection, path) => {
    const url = `/collection/${encodeURIComponent(collection)}/documents/${encodeURIComponent(path)}`
    console.log('[ragAPI] 删除文档 - URL:', url)
    return apiClient.delete(url).then(handleRagResponse)
  },

  viewDocumentChunks: (collection, path) => {
    const url = `/collection/${encodeURIComponent(collection)}/documents/${encodeURIComponent(path)}/chunks`
    console.log('[ragAPI] 查看切片 - URL:', url)
    return apiClient.get(url).then(handleRagResponse)
  },

  triggerSync: (collection, fullSync = false) => {
    const body = {}
    if (collection) body.collection = collection
    if (fullSync) body.full_sync = true
    return apiClient.post('/rag/sync', body).then(handleRagResponse)
  },

  getSyncStatus: () => {
    return apiClient.get('/rag/sync/status').then(handleRagResponse)
  },

  getSyncHistory: (limit = 20) => {
    return apiClient.get('/rag/sync/history', { params: { limit } }).then(handleRagResponse)
  },

  getSyncChanges: (limit = 50, collection) => {
    const params = { limit }
    if (collection) params.collection = collection
    return apiClient.get('/rag/sync/changes', { params }).then(handleRagResponse)
  },

  startSyncMonitor: () => {
    return apiClient.post('/rag/sync/start').then(handleRagResponse)
  },

  stopSyncMonitor: () => {
    return apiClient.post('/rag/sync/stop').then(handleRagResponse)
  },

  generateExam: (params) => {
    return apiClient.post('/exam/generate', params, {
      timeout: 120000
    }).then(handleRagResponse)
  },

  gradeExam: (params) => {
    return apiClient.post('/exam/grade', params, {
      timeout: 120000
    }).then(handleRagResponse)
  },

  search: (params) => {
    return apiClient.post('/rag/search', params).then(handleRagResponse)
  },

  cascadeDelete: (fileId) => {
    return apiClient.post(`/collection/cascade-delete/${fileId}`, {}, { timeout: 60000 }).then(handleRagResponse)
  },

  devectorize: (collectionName, fileId) => {
    return apiClient.post(`/collection/${collectionName}/devectorize`, null, {
      params: { fileId },
      timeout: 120000
    }).then(handleRagResponse)
  },

  generateExamForFile: (params) => {
    const { collectionName, ...rest } = params
    // 按文档5.2.3规范：所有参数作为 query param 传递
    return apiClient.post(`/collection/${collectionName}/generate-exam`, null, {
      params: rest,
      timeout: 180000
    }).then(handleRagResponse)
  }
}

export default ragAPI
