/**
 * 考试模块 API
 */
import request from '../request'

// 题目类型
export type QuestionType = 'single' | 'multiple' | 'judge' | 'fill'

// 题目选项
export interface QuestionOption {
  id: string
  content: string
  isCorrect?: boolean
}

// 题目信息
export interface Question {
  id: string
  type: QuestionType
  content: string
  options?: QuestionOption[]
  correctAnswer: string
  explanation: string
  difficulty: 'easy' | 'medium' | 'hard'
  subject: string
  tags: string[]
  score: number
}

// 考试配置
export interface ExamConfig {
  courseId?: number
  questionCount: number
  difficulty?: 'easy' | 'medium' | 'hard'
  subjects?: string[]
  tags?: string[]
  timeLimit?: number // 分钟
  passingScore?: number
}

// 考试实例
export interface ExamInstance {
  id: string
  name: string
  type: 'practice' | 'formal' | 'mock'
  config: ExamConfig
  questions: Question[]
  totalScore: number
  timeLimit?: number
  status: 'not_started' | 'in_progress' | 'completed' | 'timeout'
  startTime?: string
  endTime?: string
  createdAt: string
}

// 考试答案
export interface ExamAnswer {
  questionId: string
  answer: string | string[]
  isCorrect?: boolean
  score?: number
  timeSpent?: number // 秒
}

// 考试提交数据
export interface ExamSubmission {
  examId: string
  answers: ExamAnswer[]
  submitTime: string
  totalTimeSpent: number // 秒
}

// 考试结果
export interface ExamResult {
  id: string
  examId: string
  examName: string
  examType: string
  userId: number
  userName: string
  totalScore: number
  userScore: number
  accuracy: number
  passingScore: number
  isPassed: boolean
  timeSpent: number
  answers: Array<ExamAnswer & {
    question: Question
  }>
  scoreByType: Array<{
    type: QuestionType
    totalQuestions: number
    correctAnswers: number
    accuracy: number
    score: number
    maxScore: number
  }>
  scoreBySubject: Array<{
    subject: string
    totalQuestions: number
    correctAnswers: number
    accuracy: number
    score: number
    maxScore: number
  }>
  startTime: string
  endTime: string
  createdAt: string
}

// 动态考试轮次结果
export interface ExamRoundResult {
  round: number
  question: Question
  userAnswer: string | string[]
  isCorrect: boolean
  score: number
  timeSpent: number
  explanation: string
}

// 动态考试会话
export interface DynamicExamSession {
  sessionId: string
  courseId?: number
  currentRound: number
  totalRounds: number
  currentScore: number
  averageScore: number
  correctCount: number
  incorrectCount: number
  status: 'active' | 'completed' | 'timeout'
  rounds: ExamRoundResult[]
  startTime: string
  lastActiveTime: string
}

/**
 * 开始动态考试
 */
export const startDynamicExam = (config: {
  courseId?: number
  totalRounds?: number
  difficulty?: string
  subject?: string
}) => {
  return request.post<{
    sessionId: string
    firstQuestion: Question
    session: DynamicExamSession
  }>('/api/v1/exams/dynamic/start', config)
}

/**
 * 提交动态考试答案并获取下一题
 */
export const submitDynamicAnswer = (data: {
  sessionId: string
  questionId: string
  answer: string | string[]
  timeSpent?: number
}) => {
  return request.post<{
    result: ExamRoundResult
    nextQuestion?: Question
    session: DynamicExamSession
    isCompleted: boolean
  }>('/api/v1/exams/dynamic/submit', data)
}

/**
 * 获取动态考试会话状态
 */
export const getDynamicExamSession = (sessionId: string) => {
  return request.get<DynamicExamSession>(`/api/v1/exams/dynamic/sessions/${sessionId}`)
}

/**
 * 结束动态考试
 */
export const endDynamicExam = (sessionId: string) => {
  return request.post<{
    result: ExamResult
    session: DynamicExamSession
  }>(`/api/v1/exams/dynamic/sessions/${sessionId}/end`)
}

/**
 * 创建标准考试
 */
export const createExam = (config: ExamConfig) => {
  return request.post<ExamInstance>('/api/v1/exams/create', config)
}

/**
 * 获取考试详情
 */
export const getExamDetail = (examId: string) => {
  return request.get<ExamInstance>(`/api/v1/exams/${examId}`)
}

/**
 * 开始考试
 */
export const startExam = (examId: string) => {
  return request.post<{
    exam: ExamInstance
    startTime: string
  }>(`/api/v1/exams/${examId}/start`)
}

/**
 * 提交考试
 */
export const submitExam = (submission: ExamSubmission) => {
  return request.post<ExamResult>('/api/v1/exams/submit', submission)
}

/**
 * 获取考试结果
 */
export const getExamResult = (resultId: string) => {
  return request.get<ExamResult>(`/api/v1/exams/results/${resultId}`)
}

/**
 * 获取用户考试记录列表
 */
export const getUserExamRecords = (params: {
  page?: number
  size?: number
  examType?: string
  subject?: string
  status?: string
  startDate?: string
  endDate?: string
} = {}) => {
  return request.get<{
    items: ExamResult[]
    total: number
    page: number
    size: number
    statistics: {
      totalExams: number
      passedExams: number
      averageScore: number
      averageAccuracy: number
      totalTimeSpent: number
      bestScore: number
      recentImprovement: number
    }
  }>('/api/v1/exams/records', { params })
}

/**
 * 获取错题统计
 */
export const getMistakeStatistics = (params: {
  subject?: string
  difficulty?: string
  tags?: string[]
  startDate?: string
  endDate?: string
} = {}) => {
  return request.get<{
    totalMistakes: number
    masteredCount: number
    unmasteredCount: number
    recentMistakes: number
    mistakesBySubject: Array<{
      subject: string
      count: number
      masteredCount: number
    }>
    mistakesByDifficulty: Array<{
      difficulty: string
      count: number
      masteredCount: number
    }>
    mistakesByType: Array<{
      type: QuestionType
      count: number
      masteredCount: number
    }>
  }>('/api/v1/exams/mistakes/statistics', { params })
}

/**
 * 获取错题列表
 */
export const getMistakeQuestions = (params: {
  page?: number
  size?: number
  subject?: string
  difficulty?: string
  type?: QuestionType
  isMastered?: boolean
  tags?: string[]
  keyword?: string
} = {}) => {
  return request.get<{
    items: Array<{
      id: string
      question: Question
      mistakeCount: number
      lastMistakeTime: string
      firstMistakeTime: string
      isMastered: boolean
      userAnswers: string[]
      examSources: Array<{
        examId: string
        examName: string
        examTime: string
      }>
    }>
    total: number
    page: number
    size: number
  }>('/api/v1/exams/mistakes', { params })
}

/**
 * 标记错题为已掌握
 */
export const markMistakeAsMastered = (questionId: string) => {
  return request.post(`/api/v1/exams/mistakes/${questionId}/mastered`)
}

/**
 * 错题重练
 */
export const practiceeMistakes = (questionIds: string[]) => {
  return request.post<{
    examId: string
    questions: Question[]
  }>('/api/v1/exams/mistakes/practice', { questionIds })
}

/**
 * 获取推荐练习题
 */
export const getRecommendedQuestions = (params: {
  courseId?: number
  weakSubjects?: string[]
  difficulty?: string
  count?: number
}) => {
  return request.get<{
    questions: Question[]
    reason: string
    estimatedTime: number
  }>('/api/v1/exams/recommend', { params })
}

// ==================== 成绩报告和错题本相关API ====================

/**
 * 三轮得分
 */
export interface RoundScores {
  round1: number | null
  round2: number | null
  round3: number | null
}

/**
 * 成绩报告概览
 */
export interface ExamReportOverview {
  avg_score: number
  total_exams: number
  pass_rate: number
  total_questions: number
}

/**
 * 成绩趋势项
 */
export interface ExamTrendItem {
  date: string
  avg_score: number
}

/**
 * 科目统计项
 */
export interface SubjectStatItem {
  course_id: number
  course_name: string
  avg_score: number
  exam_count: number
  max_score: number
  min_score: number
  pass_rate: number
}

/**
 * 最近考试记录项
 */
export interface RecentExamItem {
  id: number
  course_id: number
  course_name: string
  score: number | null
  total_score: number
  is_passed: boolean | null
  duration_seconds: number | null
  start_time: string
  end_time: string | null
  round_scores: RoundScores
}

/**
 * 成绩报告响应
 */
export interface ExamReportResponse {
  overview: ExamReportOverview
  trends: ExamTrendItem[]
  subjects: SubjectStatItem[]
  recent_exams: RecentExamItem[]
}

/**
 * 错题列表项
 */
export interface MistakeListItem {
  id: number
  exam_id: number
  course_id: number
  course_name: string
  question_content: string
  correct_answer: string
  user_answer: string
  question_type: string | null
  knowledge_point_id: number | null
  knowledge_point_name: string | null
  created_at: string
}

/**
 * 错题列表响应
 */
export interface MistakeListResponse {
  items: MistakeListItem[]
  total: number
  page: number
  size: number
  pages: number
}

/**
 * 按课程统计错题
 */
export interface MistakeByCourse {
  course_id: number
  course_name: string
  count: number
}

/**
 * 按题型统计错题
 */
export interface MistakeByType {
  type: string
  type_name: string
  count: number
}

/**
 * 按时间统计错题
 */
export interface MistakeByTime {
  week: number
  month: number
  quarter: number
}

/**
 * 错题统计响应
 */
export interface MistakesStatisticsResponse {
  total: number
  by_course: MistakeByCourse[]
  by_type: MistakeByType[]
  by_time: MistakeByTime
}

/**
 * 获取成绩报告
 */
export const getExamReport = (params?: {
  start_date?: string
  end_date?: string
}) => {
  return request.get<ExamReportResponse>('/api/v1/exams/statistics/report', { params })
}

/**
 * 获取错题列表（扩展版）
 */
export const getMistakesList = (params: {
  exam_id?: number
  course_id?: number
  question_type?: string
  search?: string
  start_date?: string
  end_date?: string
  page?: number
  size?: number
}) => {
  return request.get<MistakeListResponse>('/api/v1/exams/mistakes/list', { params })
}

/**
 * 获取错题统计
 */
export const getMistakesStatistics = (params?: {
  course_id?: number
}) => {
  return request.get<MistakesStatisticsResponse>('/api/v1/exams/mistakes/statistics', { params })
}

/**
 * 更新轮次得分
 */
export const updateRoundScore = (data: {
  exam_id: number
  round: number
  score: number
  is_final?: boolean
}) => {
  return request.put<{ exam_id: number }>(`/api/v1/exams/${data.exam_id}/round-score`, {
    round: data.round,
    score: data.score,
    is_final: data.is_final
  })
}

/**
 * 标记错题为已掌握
 */
export const markMistakeMastered = (mistakeId: number) => {
  return request.put<{ mistake_id: number; mastery_status: string }>(
    `/api/v1/exams/mistakes/${mistakeId}/mastered`
  )
}
