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

const EXAM_API_BASE_URL = import.meta.env.VITE_EXAM_API_BASE_URL || '/api'

const examClient = axios.create({
  baseURL: EXAM_API_BASE_URL,
  timeout: 120000,
  headers: { 'Content-Type': 'application/json' }
})

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

examClient.interceptors.response.use(
  response => response,
  error => {
    const status = error.response?.status

    if (status === 401) {
      handleAuthError()
      return Promise.reject(error)
    }

    if (status === 403) {
      const err = new Error('权限不足，请联系管理员提升权限')
      err.code = 'EXAM_403'
      err.status = 403
      err.originalError = error
      return Promise.reject(err)
    }

    const errorMessages = {
      400: error.response?.data?.message || '请求参数错误',
      404: '接口不存在，请检查后端服务是否已部署',
      405: '请求方法不允许',
      500: error.response?.data?.message || '服务器内部错误'
    }

    const errorMsg = errorMessages[status] || (error.response ? '请求失败' : '网络连接失败')

    const err = new Error(errorMsg)
    err.code = `EXAM_${status || 'NETWORK'}`
    err.status = status
    err.originalError = error
    return Promise.reject(err)
  }
)

function handleExamResponse(response) {
  const data = response.data
  if (!data) {
    const err = new Error('服务器返回空数据')
    err.response = response
    throw err
  }
  if (data.code === 200 && data.data !== undefined && data.data !== null) return data.data
  if (data.code !== 200 && data.code !== undefined) {
    const bizErr = new Error(data.message || data.msg || `请求失败 (code: ${data.code})`)
    bizErr.code = `EXAM_BIZ_${data.code}`
    bizErr.bizCode = data.code
    bizErr.response = response
    throw bizErr
  }
  return data
}

function validatePositiveInteger(value, fieldName, max) {
  if (value === undefined || value === null) return 0
  const num = Number(value)
  if (!Number.isInteger(num) || num < 0) throw new Error(`${fieldName}必须为非负整数`)
  if (max !== undefined && num > max) throw new Error(`${fieldName}不能超过${max}`)
  return num
}

function validateDifficulty(value) {
  if (value === undefined || value === null) return 2
  const num = Number(value)
  if (!Number.isInteger(num) || num < 1 || num > 5) throw new Error('难度等级必须为1-5的整数')
  return num
}

export const examAPI = {

  getPendingList: () => {
    return examClient.get('/exam/paper/pending', { timeout: 30000 }).then(handleExamResponse)
  },

  start: (paperId) => {
    return examClient.post(`/exam/paper/${encodeURIComponent(paperId)}/start`, {}, { timeout: 15000 }).then(handleExamResponse)
  },

  /**
   * @deprecated 使用 submitFormalExam 或 gradeAnswers 替代
   * 提交考试答案并批改，空白提交也通过 grade 接口处理
   */
  submit: (recordId, answers) => {
    const hasAnswers = answers && Array.isArray(answers) && answers.length > 0
    console.log(`[examAPI] submit - recordId:${recordId}, 答案数:${hasAnswers ? answers.length : 0}`)
    return examClient.post(`/exam/record/${encodeURIComponent(recordId)}/grade`, { answers: hasAnswers ? answers : [] }, { timeout: 120000 }).then(handleExamResponse)
  },

  getResults: () => {
    return examClient.get('/exam/records', { params: { type: 'formal_exam', _t: Date.now() }, timeout: 30000 }).then(handleExamResponse)
  },

  generateQuestions: (params) => {
    const hasFileId = params.file_id != null
    const hasFilePath = !!params.file_path
    if (!hasFileId && !hasFilePath) throw new Error('file_id 或 file_path 不能为空')

    const requestBody = {}

    // 按文档规范：推荐使用 file_id（自动查询向量库）
    if (hasFileId) {
      requestBody.file_id = Number(params.file_id)
    }

    // 使用 file_path 时必须提供 collection
    if (hasFilePath) {
      requestBody.file_path = params.file_path
      requestBody.collection = params.collection || 'public_kb'
    }

    requestBody.question_types = params.question_types || {}
    if (params.question_scores) requestBody.question_scores = params.question_scores
    requestBody.difficulty = validateDifficulty(params.difficulty)
    requestBody.request_id = params.request_id || `gen_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

    return examClient.post('/exam/generate', requestBody, { timeout: 280000 }).then(handleExamResponse)
  },

  generatePaper: (params) => {
    const singleCount = validatePositiveInteger(params.single_choice_count, '单选题数量', 50)
    const multipleCount = validatePositiveInteger(params.multiple_choice_count, '多选题数量', 50)
    const trueFalseCount = validatePositiveInteger(params.true_false_count, '判断题数量', 50)
    const fillBlankCount = validatePositiveInteger(params.fill_blank_count, '填空题数量', 50)
    const subjectiveCount = validatePositiveInteger(params.subjective_count, '简答题数量', 20)

    const totalCount = singleCount + multipleCount + trueFalseCount + fillBlankCount + subjectiveCount
    if (totalCount === 0) throw new Error('至少需要设置一种题型的数量')

    const requestBody = {
      single_choice_count: singleCount,
      multiple_choice_count: multipleCount,
      true_false_count: trueFalseCount,
      fill_blank_count: fillBlankCount,
      subjective_count: subjectiveCount,
      include_personal: Boolean(params.include_personal),
      difficulty: validateDifficulty(params.difficulty)
    }

    // Only add file_ids when explicitly provided and non-empty (bug fix: empty [] caused 0 questions)
    if (Array.isArray(params.file_ids) && params.file_ids.length > 0) {
      requestBody.file_ids = params.file_ids.filter(id => id != null).map(Number)
    }

    console.log('[examAPI] 生成试卷 - 参数:', requestBody)

    return examClient.post('/exam/paper/generate', requestBody, { timeout: 120000 })
      .then(handleExamResponse)
      .then(response => {
        console.log('[examAPI] 试卷生成成功:', response)
        return response
      })
  },

  gradeAnswers: (params) => {
    if (!params.answers || !Array.isArray(params.answers)) {
      params.answers = []
    }

    const answers = params.answers.map((answer, idx) => {
      if (!answer.questionId && !answer.question_id) throw new Error(`第${idx + 1}个答案的question_id不能为空`)
      if (!answer.questionType && !answer.question_type) throw new Error(`第${idx + 1}个答案的question_type不能为空`)

      return {
        question_id: String(answer.questionId || answer.question_id),
        question_type: answer.questionType || answer.question_type,
        question_content: answer.questionContent || answer.question_content || {},
        student_answer: answer.studentAnswer != null ? answer.studentAnswer : (answer.student_answer != null ? answer.student_answer : ''),
        max_score: answer.maxScore != null ? Number(answer.maxScore) : (answer.max_score != null ? Number(answer.max_score) : 5)
      }
    })

    const isBlank = answers.length === 0
    const requestBody = {
      request_id: params.requestId || params.request_id || `grade_${Date.now()}`,
      answer_type: params.type || params.answer_type || 'practice',
      record_id: params.recordId || params.record_id || null,
      answers
    }

    console.log('[examAPI] 批改答案 - 参数:', { answer_type: requestBody.answer_type, record_id: requestBody.record_id, answersCount: answers.length })
    console.log('[examAPI] 发送完整 payload:', JSON.stringify(requestBody, null, 2)?.substring(0, 1000))
    if (isBlank) console.log('[examAPI] ⚠️ 空白试卷提交')

    return examClient.post('/exam/grade', requestBody, { timeout: 120000 }).then(handleExamResponse)
  },

  queryUserAnswers: (params) => {
    const hasPaperId = params.paper_id && String(params.paper_id).trim()
    const hasSessionId = params.session_id && String(params.session_id).trim()
    const hasRecordId = params.record_id && String(params.record_id).trim()

    if (!hasPaperId && !hasSessionId && !hasRecordId) throw new Error('paper_id、session_id 或 record_id 不能为空')
    if ([hasPaperId, hasSessionId, hasRecordId].filter(Boolean).length > 1) throw new Error('只能提供 paper_id、session_id、record_id 中的一个')

    const requestBody = {}
    if (hasRecordId) requestBody.record_id = String(params.record_id)
    else if (hasPaperId) requestBody.paper_id = String(params.paper_id)
    else if (hasSessionId) requestBody.session_id = String(params.session_id)

    if (params.answer_type) requestBody.answer_type = params.answer_type
    if (params.page != null) requestBody.page = Number(params.page)
    if (params.page_size != null) requestBody.page_size = Number(params.page_size)

    return examClient.post('/exam/answers/query', requestBody, { timeout: 30000 }).then(handleExamResponse)
  },

  /**
   * 统一考试记录查询接口
   * 替代废弃的 /exam/my/papers 和 /formal-exam/my/papers
   */
  getExamRecords: (type = 'formal_exam') => {
    const validTypes = ['practice', 'mock_exam', 'formal_exam']
    if (!validTypes.includes(type)) throw new Error(`无效的类型参数，支持的值: ${validTypes.join(', ')}`)
    return examClient.get('/exam/records', { params: { type }, timeout: 30000 }).then(handleExamResponse)
  },

  getPaperDetail: (paperId) => {
    if (!paperId) throw new Error('试卷ID不能为空')
    return examClient.get(`/exam/paper/${encodeURIComponent(paperId)}`, { timeout: 30000 }).then(handleExamResponse)
  },

  startExamByPaperId: (paperId) => {
    if (!paperId) throw new Error('试卷ID不能为空')
    console.log('[examAPI] 开始考试（通过paperId）:', paperId)
    return examClient.post(`/exam/paper/${encodeURIComponent(paperId)}/start`, {}, { timeout: 15000 }).then(handleExamResponse)
  },

  /**
   * 正式考试：通过试卷ID开始考试
   * 使用 /formal-exam 前缀，answerType=formal_exam
   */
  startFormalExamByPaperId: (paperId) => {
    if (!paperId) throw new Error('试卷ID不能为空')
    console.log('[examAPI] 开始正式考试（通过paperId）:', paperId)
    return examClient.post(`/formal-exam/paper/${encodeURIComponent(paperId)}/start`, {}, { timeout: 15000 }).then(handleExamResponse)
  },

  /**
   * @deprecated 使用 startExamByPaperId 替代
   * 旧接口：POST /api/exam/record/{recordId}/start (V2.9.1已废弃)
   */
  startExamRecord: (recordId) => {
    console.warn('[examAPI] ⚠️ startExamRecord 已废弃，请使用 startExamByPaperId')
    if (!recordId) throw new Error('考试记录ID不能为空')
    return examClient.post(`/exam/record/${encodeURIComponent(recordId)}/start`, {}, { timeout: 15000 }).then(handleExamResponse)
  },

  getExamResult: (recordId) => {
    if (!recordId) throw new Error('考试记录ID不能为空')
    return examClient.get(`/exam/record/${encodeURIComponent(recordId)}/result`, { timeout: 30000 }).then(handleExamResponse)
  },

  /**
   * 正式考试结果详情接口
   * 接口路径: GET /api/formal-exam/record/{recordId}/result
   * 功能说明: 获取考试结果详情，包含每题得分和反馈
   */
  getFormalExamResult: (recordId) => {
    if (!recordId) throw new Error('考试记录ID不能为空')
    return examClient.get(`/formal-exam/record/${encodeURIComponent(recordId)}/result`, { timeout: 30000 }).then(handleExamResponse)
  },

  /**
   * 正式考试提交（文档 2.4 节/14.2 推荐接口）
   * 接口路径：POST /api/exam/record/{recordId}/grade
   * 功能：通过 recordId 提交正式考试答案并自动批改
   * 参数格式严格遵循文档 2.4 节规范
   */
  submitFormalExam: ({ recordId, answers }) => {
    if (!recordId) throw new Error('考试记录ID不能为空')
    if (!answers || !Array.isArray(answers)) throw new Error('答案列表不能为空')

    answers.forEach((a, i) => {
      if (!a.questionId) throw new Error(`第${i + 1}个答案的questionId不能为空`)
      if (!a.questionType) throw new Error(`第${i + 1}个答案的questionType不能为空`)
    })

    const cleanAnswers = answers.map(a => ({
      questionId: String(a.questionId || a.question_id),
      questionType: a.questionType || a.question_type,
      answer: a.studentAnswer != null ? a.studentAnswer : (a.student_answer != null ? a.student_answer : a.answer || '')
    }))

    console.log('[examAPI] 正式考试提交(14.2格式) - recordId:', recordId, '题目数:', cleanAnswers.length)

    return examClient.post(`/exam/record/${encodeURIComponent(recordId)}/grade`, { answers: cleanAnswers }, { timeout: 120000 })
      .then(response => {
        const payload = response.data
        if (!payload) throw Object.assign(new Error('服务器返回空数据'), { response })
        if (payload.code === 200 && payload.data !== undefined && payload.data !== null) return payload.data
        if (payload.code !== 200 && payload.code !== undefined) {
          const bizErr = new Error(payload.message || payload.msg || `请求失败 (code: ${payload.code})`)
          bizErr.code = `EXAM_BIZ_${payload.code}`
          bizErr.bizCode = payload.code
          bizErr.response = response
          throw bizErr
        }
        return payload
      })
  },

  /**
   * @deprecated V2.9.3已废弃
   * 请使用 gradeExamRecord 或 gradeAnswers 替代
   */
  saveExamAnswer: (recordId, answers) => {
    console.warn('[examAPI] ⚠️ saveExamAnswer 已废弃，建议使用 gradeAnswers 或 gradeExamRecord')
    if (!recordId) throw new Error('考试记录ID不能为空')
    if (!answers || typeof answers !== 'object') throw new Error('答案数据不能为空')
    return examClient.put(`/exam/record/${encodeURIComponent(recordId)}/save`, { answers }, { timeout: 15000 }).then(handleExamResponse)
  },

  /**
   * @deprecated V2.9.3已废弃
   * 正式考试请使用 gradeExamRecord，日常练习请使用 gradeAnswers
   */
  submitExamRecord: (recordId) => {
    console.warn('[examAPI] ⚠️ submitExamRecord 已废弃，请使用 gradeExamRecord 或 gradeAnswers')
    if (!recordId) throw new Error('考试记录ID不能为空')
    return examClient.post(`/exam/record/${encodeURIComponent(recordId)}/submit`, {}, { timeout: 120000 }).then(handleExamResponse)
  },

  publishPaper: (paperId, params = {}) => {
    if (!paperId) throw new Error('试卷ID不能为空')
    // 直接转发 params 的字段，与后端 ExamPublishRequest 保持字段名一致
    const body = {
      deptId: params.deptId ?? null,
      deptIds: params.deptIds || [],
      userIds: params.userIds || [],
      excludeUserIds: params.excludeUserIds || [],
      publishTime: params.publishTime || null,
      deadline: params.deadline || null
    }
    // 移除所有 null 字段（只传有值的字段），避免 LocalDateTime 反序列化问题
    Object.keys(body).forEach(k => { if (body[k] === null) delete body[k] })
    console.log('[examAPI] 发布试卷 - 参数:', { paperId, ...body })
    return examClient.post(`/admin/exam/paper/${encodeURIComponent(paperId)}/publish`, body, { timeout: 30000 }).then(handleExamResponse)
  },

  previewPaperWithDetails: (params) => {
    const requestBody = {}
    if (params.single_choice_count != null) requestBody.single_choice_count = validatePositiveInteger(params.single_choice_count, '单选题数量', 50)
    if (params.multiple_choice_count != null) requestBody.multiple_choice_count = validatePositiveInteger(params.multiple_choice_count, '多选题数量', 50)
    if (params.true_false_count != null) requestBody.true_false_count = validatePositiveInteger(params.true_false_count, '判断题数量', 50)
    if (params.fill_blank_count != null) requestBody.fill_blank_count = validatePositiveInteger(params.fill_blank_count, '填空题数量', 50)
    if (params.subjective_count != null) requestBody.subjective_count = validatePositiveInteger(params.subjective_count, '简答题数量', 20)
    if (params.difficulty != null) requestBody.difficulty = validateDifficulty(params.difficulty)
    if (params.include_personal != null) requestBody.include_personal = Boolean(params.include_personal)
    if (Array.isArray(params.file_ids) && params.file_ids.length > 0) requestBody.file_ids = params.file_ids.filter(id => id != null).map(Number)

    console.log('[examAPI] 预览试卷详情 - 参数:', requestBody)
    return examClient.post('/admin/exam/paper/preview', requestBody, { timeout: 120000 }).then(handleExamResponse)
  },

  getPaperAssignment: (paperId) => {
    if (!paperId) throw new Error('试卷ID不能为空')
    return examClient.get(`/admin/exam/paper/${encodeURIComponent(paperId)}/assignment`, { timeout: 30000 }).then(handleExamResponse)
  },

  savePaper: (data) => {
    if (!data.title || !data.title.trim()) throw new Error('试卷标题不能为空')
    if (!data.questionIds || !Array.isArray(data.questionIds) || data.questionIds.length === 0) throw new Error('题目ID列表不能为空')
    return examClient.post('/admin/exam/paper/save', data, { timeout: 30000 }).then(handleExamResponse)
  },

  getAdminPapers: () => {
    return examClient.get('/admin/exam/paper/list', { timeout: 30000 }).then(handleExamResponse)
  },

  getAdminPapersPaginated: (page = 1, pageSize = 10) => {
    return examClient.get('/admin/exam/paper/list', { params: { page, pageSize }, timeout: 30000 })
      .then(response => {
        const data = handleExamResponse(response)
        return { records: data?.records || [], total: data?.total || 0, page: data?.page || page, pageSize: data?.pageSize || pageSize }
      })
  },

  getAdminPapersByFileId: async (fileId) => {
    const response = await examClient.get('/admin/exam/paper/list', { timeout: 30000 })
    const data = handleExamResponse(response)
    const allPapers = data?.records || data?.list || (Array.isArray(data) ? data : [])
    const matchingPapers = []
    if (Array.isArray(allPapers) && fileId) {
      for (const paper of allPapers) {
        if (paper.questions && paper.questions.length > 0) {
          for (const q of paper.questions) {
            if (q.fileId === fileId || String(q.fileId) === String(fileId)) {
              matchingPapers.push(paper)
              break
            }
          }
        }
      }
    }
    return { records: matchingPapers, total: matchingPapers.length }
  },

  getAdminPaperDetail: (paperId) => {
    if (!paperId) throw new Error('试卷ID不能为空')
    return examClient.get(`/admin/exam/paper/${encodeURIComponent(paperId)}`, { timeout: 30000 }).then(handleExamResponse)
  },

  revokePaper: (paperId) => {
    if (!paperId) throw new Error('试卷ID不能为空')
    return examClient.post(`/admin/exam/paper/${encodeURIComponent(paperId)}/revoke`, {}, { timeout: 15000 }).then(handleExamResponse)
  },

  deleteAdminPaper: (paperId) => {
    if (!paperId) throw new Error('试卷ID不能为空')
    return examClient.delete(`/admin/exam/paper/${encodeURIComponent(paperId)}`, { timeout: 15000 }).then(handleExamResponse)
  },

  getAdminExamRecords: (paperId) => {
    if (!paperId) throw new Error('试卷ID不能为空')
    return examClient.get(`/admin/exam/records/${encodeURIComponent(paperId)}`, { timeout: 30000 }).then(handleExamResponse)
  },

  getAdminExamRecordDetail: (recordId) => {
    if (!recordId) throw new Error('考试记录ID不能为空')
    return examClient.get(`/admin/exam/record/${encodeURIComponent(recordId)}`, { timeout: 30000 }).then(handleExamResponse)
  }
}
export default examAPI
