import "server-only"

import { cache } from "react"
import { and, desc, eq, inArray, isNull, lte, or } from "drizzle-orm"

import { db } from "@/shared/db"
import {
  homeworkAnswers,
  homeworkAssignmentQuestions,
  homeworkAssignmentTargets,
  homeworkAssignments,
  homeworkSubmissions,
} from "@/shared/db/schema"
import { getExamSubjectIdMap, getExamForProctoringCrossModule } from "@/modules/exams/data-access"
import { getSubjectOptions } from "@/modules/school/data-access"

import {
  getHomeworkSubmissionDetails,
  getAssignmentMaxScoreById,
  toQuestionContent,
  toHomeworkSubmissionStatus,
} from "./data-access"
import type {
  HomeworkSubmissionDetails,
  StudentHomeworkAssignmentListItem,
  StudentHomeworkProgressStatus,
  StudentHomeworkTakeData,
} from "./types"

const toStudentProgressStatus = (v: string | null | undefined): StudentHomeworkProgressStatus => {
  if (v === "started") return "in_progress"
  if (v === "submitted") return "submitted"
  if (v === "graded") return "graded"
  return "not_started"
}

/**
 * V3-9: 获取学生在指定作业的最新提交结果（用于提交后反馈页）
 *
 * 查找学生最近一次已提交/已批改的 submission，返回完整详情含答案。
 */
export const getStudentSubmissionResult = cache(async (
  assignmentId: string,
  studentId: string
): Promise<HomeworkSubmissionDetails | null> => {
  const latestSubmission = await db.query.homeworkSubmissions.findFirst({
    where: and(
      eq(homeworkSubmissions.assignmentId, assignmentId),
      eq(homeworkSubmissions.studentId, studentId),
      inArray(homeworkSubmissions.status, ["submitted", "graded"])
    ),
    orderBy: [desc(homeworkSubmissions.updatedAt)],
    columns: { id: true },
  })

  if (!latestSubmission) return null

  return getHomeworkSubmissionDetails(latestSubmission.id)
})

/**
 * V3-11: 获取学生的考试结果列表（供家长端展示）
 *
 * 查找学生所有已批改的、关联到考试的作业提交，
 * 返回考试标题、科目、分数、提交时间等。
 */
export const getStudentExamResults = cache(async (studentId: string): Promise<Array<{
  submissionId: string
  examId: string
  examTitle: string
  assignmentId: string
  assignmentTitle: string
  score: number
  maxScore: number
  submittedAt: string | null
  status: string
}>> => {
  const submissions = await db.query.homeworkSubmissions.findMany({
    where: and(
      eq(homeworkSubmissions.studentId, studentId),
      eq(homeworkSubmissions.status, "graded")
    ),
    with: {
      assignment: {
        with: { sourceExam: true },
      },
    },
    orderBy: [desc(homeworkSubmissions.updatedAt)],
    limit: 50,
  })

  // Filter to only exam-linked submissions, deduplicate by examId
  const latestByExamId = new Map<string, (typeof submissions)[number]>()
  for (const s of submissions) {
    const examId = s.assignment.sourceExamId
    if (!examId) continue
    if (!latestByExamId.has(examId)) latestByExamId.set(examId, s)
  }

  const examIds = Array.from(latestByExamId.keys())
  if (examIds.length === 0) return []

  // Get max scores for each assignment
  const assignmentIds = Array.from(latestByExamId.values()).map((s) => s.assignmentId)
  const maxScoreMap = await getAssignmentMaxScoreById(assignmentIds)

  return Array.from(latestByExamId.entries()).map(([examId, s]) => ({
    submissionId: s.id,
    examId,
    examTitle: s.assignment.sourceExam?.title ?? s.assignment.title,
    assignmentId: s.assignmentId,
    assignmentTitle: s.assignment.title,
    score: s.score ?? 0,
    maxScore: maxScoreMap.get(s.assignmentId) ?? 0,
    submittedAt: s.submittedAt ? s.submittedAt.toISOString() : null,
    status: s.status ?? "graded",
  }))
})

export const getStudentHomeworkAssignments = cache(async (studentId: string): Promise<StudentHomeworkAssignmentListItem[]> => {
  const now = new Date()

  const targetAssignmentIds = db
    .select({ assignmentId: homeworkAssignmentTargets.assignmentId })
    .from(homeworkAssignmentTargets)
    .where(eq(homeworkAssignmentTargets.studentId, studentId))

  const assignments = await db
    .select({
      id: homeworkAssignments.id,
      title: homeworkAssignments.title,
      sourceExamId: homeworkAssignments.sourceExamId,
      dueAt: homeworkAssignments.dueAt,
      availableAt: homeworkAssignments.availableAt,
      maxAttempts: homeworkAssignments.maxAttempts,
      createdAt: homeworkAssignments.createdAt,
    })
    .from(homeworkAssignments)
    .where(
      and(
        eq(homeworkAssignments.status, "published"),
        inArray(homeworkAssignments.id, targetAssignmentIds),
        or(isNull(homeworkAssignments.availableAt), lte(homeworkAssignments.availableAt, now))
      )
    )
    .orderBy(desc(homeworkAssignments.dueAt), desc(homeworkAssignments.createdAt))

  if (assignments.length === 0) return []

  // Fetch subject names via cross-module interfaces
  // 快速作业无 sourceExamId，过滤 null 后再查询科目映射
  const examIds = assignments
    .map((a) => a.sourceExamId)
    .filter((id): id is string => id !== null)
  const [examSubjectIdMap, subjectOptions] = await Promise.all([
    getExamSubjectIdMap(examIds),
    getSubjectOptions(),
  ])
  const subjectNameById = new Map<string, string>()
  for (const s of subjectOptions) subjectNameById.set(s.id, s.name)

  const assignmentIds = assignments.map((a) => a.id)
  const submissions = await db.query.homeworkSubmissions.findMany({
    where: and(eq(homeworkSubmissions.studentId, studentId), inArray(homeworkSubmissions.assignmentId, assignmentIds)),
    orderBy: [desc(homeworkSubmissions.updatedAt)],
  })

  const attemptsByAssignmentId = new Map<string, number>()
  const latestByAssignmentId = new Map<string, (typeof submissions)[number]>()
  const latestSubmittedByAssignmentId = new Map<string, (typeof submissions)[number]>()

  for (const s of submissions) {
    attemptsByAssignmentId.set(s.assignmentId, (attemptsByAssignmentId.get(s.assignmentId) ?? 0) + 1)
    if (!latestByAssignmentId.has(s.assignmentId)) latestByAssignmentId.set(s.assignmentId, s)
    if (s.status === "submitted" || s.status === "graded") {
      if (!latestSubmittedByAssignmentId.has(s.assignmentId)) latestSubmittedByAssignmentId.set(s.assignmentId, s)
    }
  }

  return assignments.map((a) => {
    const latest = latestSubmittedByAssignmentId.get(a.id) ?? latestByAssignmentId.get(a.id) ?? null
    const attemptsUsed = attemptsByAssignmentId.get(a.id) ?? 0
    const subjectId = a.sourceExamId ? (examSubjectIdMap.get(a.sourceExamId) ?? null) : null
    const subjectName = subjectId ? subjectNameById.get(subjectId) ?? null : null

    const item: StudentHomeworkAssignmentListItem = {
      id: a.id,
      title: a.title,
      subjectName: subjectName ?? null,
      dueAt: a.dueAt ? a.dueAt.toISOString() : null,
      availableAt: a.availableAt ? a.availableAt.toISOString() : null,
      maxAttempts: a.maxAttempts,
      attemptsUsed,
      progressStatus: toStudentProgressStatus(latest?.status),
      latestSubmissionId: latest?.id ?? null,
      latestSubmittedAt: latest?.submittedAt ? latest.submittedAt.toISOString() : null,
      latestScore: latest?.score ?? null,
    }
    return item
  })
})

export const getStudentHomeworkTakeData = cache(async (assignmentId: string, studentId: string): Promise<StudentHomeworkTakeData | null> => {
  const target = await db.query.homeworkAssignmentTargets.findFirst({
    where: and(eq(homeworkAssignmentTargets.assignmentId, assignmentId), eq(homeworkAssignmentTargets.studentId, studentId)),
  })
  if (!target) return null

  const assignment = await db.query.homeworkAssignments.findFirst({
    where: eq(homeworkAssignments.id, assignmentId),
  })
  if (!assignment) return null
  if (assignment.status !== "published") return null

  const now = new Date()
  if (assignment.availableAt && assignment.availableAt > now) return null

  const startedSubmission = await db.query.homeworkSubmissions.findFirst({
    where: and(
      eq(homeworkSubmissions.assignmentId, assignmentId),
      eq(homeworkSubmissions.studentId, studentId),
      eq(homeworkSubmissions.status, "started")
    ),
    orderBy: (s, { desc }) => [desc(s.createdAt)],
  })

  const latestSubmission =
    startedSubmission ??
    (await db.query.homeworkSubmissions.findFirst({
      where: and(eq(homeworkSubmissions.assignmentId, assignmentId), eq(homeworkSubmissions.studentId, studentId)),
      orderBy: (s, { desc }) => [desc(s.createdAt)],
    }))

  const assignmentQuestions = await db.query.homeworkAssignmentQuestions.findMany({
    where: eq(homeworkAssignmentQuestions.assignmentId, assignmentId),
    with: {
      question: {
        with: {
          knowledgePoints: {
            with: {
              knowledgePoint: true
            }
          }
        }
      }
    },
    orderBy: (q, { asc }) => [asc(q.order)],
  })

  const answersByQuestionId = new Map<string, { answer: unknown; score: number | null; feedback: string | null }>()
  if (latestSubmission) {
    const answers = await db.query.homeworkAnswers.findMany({
      where: eq(homeworkAnswers.submissionId, latestSubmission.id),
    })
    for (const ans of answers) {
      answersByQuestionId.set(ans.questionId, {
        answer: ans.answerContent,
        score: ans.score,
        feedback: ans.feedback,
      })
    }
  }

  // P0-竞品修复：获取考试模式配置（仅当作业关联考试时）
  let examModeConfig: StudentHomeworkTakeData["examModeConfig"] = null
  if (assignment.sourceExamId) {
    const examConfig = await getExamForProctoringCrossModule(assignment.sourceExamId)
    if (examConfig) {
      examModeConfig = {
        examMode: (examConfig.examMode === "timed" || examConfig.examMode === "proctored" || examConfig.examMode === "homework")
          ? examConfig.examMode
          : "homework",
        durationMinutes: examConfig.durationMinutes,
        shuffleQuestions: examConfig.shuffleQuestions ?? false,
        allowLateStart: examConfig.allowLateStart ?? false,
        lateStartGraceMinutes: examConfig.lateStartGraceMinutes ?? 0,
        antiCheatEnabled: examConfig.antiCheatEnabled ?? false,
      }
    }
  }

  return {
    assignment: {
      id: assignment.id,
      title: assignment.title,
      description: assignment.description,
      availableAt: assignment.availableAt ? assignment.availableAt.toISOString() : null,
      dueAt: assignment.dueAt ? assignment.dueAt.toISOString() : null,
      allowLate: assignment.allowLate,
      lateDueAt: assignment.lateDueAt ? assignment.lateDueAt.toISOString() : null,
      maxAttempts: assignment.maxAttempts,
    },
    examModeConfig,
    submission: latestSubmission
      ? {
          id: latestSubmission.id,
          status: toHomeworkSubmissionStatus(latestSubmission.status),
          attemptNo: latestSubmission.attemptNo,
          submittedAt: latestSubmission.submittedAt ? latestSubmission.submittedAt.toISOString() : null,
          score: latestSubmission.score ?? null,
          startedAt: latestSubmission.createdAt ? latestSubmission.createdAt.toISOString() : null,
        }
      : null,
    questions: assignmentQuestions.map((aq) => {
      const saved = answersByQuestionId.get(aq.questionId)
      // Use optional chaining or fallback to empty array if knowledgePoints is not loaded/undefined
      const kps = aq.question.knowledgePoints ?? []
      return {
        questionId: aq.questionId,
        questionType: aq.question.type,
        questionContent: toQuestionContent(aq.question.content),
        maxScore: aq.score ?? 0,
        order: aq.order ?? 0,
        savedAnswer: saved?.answer ?? null,
        score: saved?.score ?? null,
        feedback: saved?.feedback ?? null,
        knowledgePoints: kps.map((kp) => ({
          id: kp.knowledgePoint.id,
          name: kp.knowledgePoint.name,
        })),
      }
    }),
  }
})
