import "server-only"

import { cache } from "react"
import { and, asc, count, desc, eq, gt, inArray, lt, sql } from "drizzle-orm"

import { db } from "@/shared/db"
import {
  homeworkAnswers,
  homeworkAssignmentQuestions,
  homeworkAssignmentTargets,
  homeworkAssignments,
  homeworkSubmissions,
} from "@/shared/db/schema"
import { isRecord } from "@/shared/lib/type-guards"
import { getStudentIdsByClassId, getStudentIdsByClassIds } from "@/modules/classes/data-access"
import { getExamIdsByGradeIds } from "@/modules/exams/data-access"

import type {
  HomeworkAssignmentListItem,
  HomeworkAssignmentReviewListItem,
  HomeworkQuestionContent,
  HomeworkAssignmentStatus,
  HomeworkSubmissionDetails,
  HomeworkSubmissionListItem,
  HomeworkSubmissionStatus,
  ExcellentSubmissionItem,
} from "./types"
import type { DataScope } from "@/shared/types/permissions"

const isHomeworkAssignmentStatus = (v: unknown): v is HomeworkAssignmentStatus =>
  v === "draft" || v === "published" || v === "archived"

const toHomeworkAssignmentStatus = (v: string | null | undefined): HomeworkAssignmentStatus =>
  isHomeworkAssignmentStatus(v) ? v : "draft"

const isHomeworkSubmissionStatus = (v: unknown): v is HomeworkSubmissionStatus =>
  v === "started" || v === "submitted" || v === "graded"

export const toHomeworkSubmissionStatus = (v: string | null | undefined): HomeworkSubmissionStatus =>
  isHomeworkSubmissionStatus(v) ? v : "started"

const isHomeworkQuestionContent = (v: unknown): v is HomeworkQuestionContent =>
  isRecord(v)

export const toQuestionContent = (v: unknown): HomeworkQuestionContent | null => {
  if (!isHomeworkQuestionContent(v)) return null
  return v
}

export const getAssignmentMaxScoreById = async (assignmentIds: string[]): Promise<Map<string, number>> => {
  const ids = assignmentIds.filter((v) => v.trim().length > 0)
  if (ids.length === 0) return new Map()

  const rows = await db
    .select({
      assignmentId: homeworkAssignmentQuestions.assignmentId,
      maxScore: sql<number>`COALESCE(SUM(${homeworkAssignmentQuestions.score}), 0)`,
    })
    .from(homeworkAssignmentQuestions)
    .where(inArray(homeworkAssignmentQuestions.assignmentId, ids))
    .groupBy(homeworkAssignmentQuestions.assignmentId)

  const map = new Map<string, number>()
  for (const r of rows) map.set(r.assignmentId, Number(r.maxScore ?? 0))
  return map
}

export const getHomeworkAssignments = cache(async (params?: { creatorId?: string; ids?: string[]; classId?: string; scope?: DataScope }) => {
  const conditions = []

  if (params?.creatorId) conditions.push(eq(homeworkAssignments.creatorId, params.creatorId))
  if (params?.ids && params.ids.length > 0) conditions.push(inArray(homeworkAssignments.id, params.ids))
  if (params?.classId) {
    const classStudentIds = await getStudentIdsByClassId(params.classId)

    const targetAssignmentIds = await db
      .selectDistinct({ assignmentId: homeworkAssignmentTargets.assignmentId })
      .from(homeworkAssignmentTargets)
      .where(inArray(homeworkAssignmentTargets.studentId, classStudentIds))

    conditions.push(inArray(homeworkAssignments.id, targetAssignmentIds.map((t) => t.assignmentId)))
  }

  // Data scope filtering
  if (params?.scope) {
    if (params.scope.type === "owned") {
      conditions.push(eq(homeworkAssignments.creatorId, params.scope.userId))
    }
    if (params.scope.type === "class_taught" && params.scope.classIds.length > 0) {
      // Filter homework by assignments targeting students in teacher's classes
      const classStudentIds = await getStudentIdsByClassIds(params.scope.classIds)

      const targetAssignmentIds = await db
        .selectDistinct({ assignmentId: homeworkAssignmentTargets.assignmentId })
        .from(homeworkAssignmentTargets)
        .where(inArray(homeworkAssignmentTargets.studentId, classStudentIds))

      conditions.push(inArray(homeworkAssignments.id, targetAssignmentIds.map((t) => t.assignmentId)))
    }
    if (params.scope.type === "grade_managed" && params.scope.gradeIds.length > 0) {
      // Homework links to exam via sourceExamId, exam has gradeId
      const gradeExamIds = await getExamIdsByGradeIds(params.scope.gradeIds)

      conditions.push(inArray(homeworkAssignments.sourceExamId, gradeExamIds))
    }
    // "all" type: no filtering
  }

  const data = await db.query.homeworkAssignments.findMany({
    where: conditions.length ? and(...conditions) : undefined,
    orderBy: [desc(homeworkAssignments.createdAt)],
    with: {
      sourceExam: true,
    },
  })

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

  const assignmentIds = data.map((a) => a.id)
  const now = new Date()

  // 并行查询：目标学生数 / 已提交数 / 已批改数 / 已批改平均分 / 逾期未提交学生集合
  const [targetCountRows, submittedCountRows, gradedCountRows, avgScoreRows, submittedStudentRows] = await Promise.all([
    db
      .select({
        assignmentId: homeworkAssignmentTargets.assignmentId,
        targetCount: sql<number>`COUNT(*)`,
      })
      .from(homeworkAssignmentTargets)
      .where(inArray(homeworkAssignmentTargets.assignmentId, assignmentIds))
      .groupBy(homeworkAssignmentTargets.assignmentId),
    db
      .select({
        assignmentId: homeworkSubmissions.assignmentId,
        submittedCount: sql<number>`COUNT(DISTINCT ${homeworkSubmissions.studentId})`,
      })
      .from(homeworkSubmissions)
      .where(
        and(
          inArray(homeworkSubmissions.assignmentId, assignmentIds),
          inArray(homeworkSubmissions.status, ["submitted", "graded"])
        )
      )
      .groupBy(homeworkSubmissions.assignmentId),
    db
      .select({
        assignmentId: homeworkSubmissions.assignmentId,
        gradedCount: sql<number>`COUNT(DISTINCT ${homeworkSubmissions.studentId})`,
      })
      .from(homeworkSubmissions)
      .where(and(inArray(homeworkSubmissions.assignmentId, assignmentIds), eq(homeworkSubmissions.status, "graded")))
      .groupBy(homeworkSubmissions.assignmentId),
    db
      .select({
        assignmentId: homeworkSubmissions.assignmentId,
        avgScore: sql<number>`AVG(${homeworkSubmissions.score})`,
      })
      .from(homeworkSubmissions)
      .where(
        and(
          inArray(homeworkSubmissions.assignmentId, assignmentIds),
          eq(homeworkSubmissions.status, "graded")
        )
      )
      .groupBy(homeworkSubmissions.assignmentId),
    db
      .select({
        assignmentId: homeworkSubmissions.assignmentId,
        studentId: homeworkSubmissions.studentId,
      })
      .from(homeworkSubmissions)
      .where(
        and(
          inArray(homeworkSubmissions.assignmentId, assignmentIds),
          inArray(homeworkSubmissions.status, ["submitted", "graded"])
        )
      ),
  ])

  const targetCountByAssignmentId = new Map<string, number>()
  for (const r of targetCountRows) targetCountByAssignmentId.set(r.assignmentId, Number(r.targetCount ?? 0))

  const submittedCountByAssignmentId = new Map<string, number>()
  for (const r of submittedCountRows) submittedCountByAssignmentId.set(r.assignmentId, Number(r.submittedCount ?? 0))

  const gradedCountByAssignmentId = new Map<string, number>()
  for (const r of gradedCountRows) gradedCountByAssignmentId.set(r.assignmentId, Number(r.gradedCount ?? 0))

  const avgScoreByAssignmentId = new Map<string, number | null>()
  for (const r of avgScoreRows) {
    const v = r.avgScore
    avgScoreByAssignmentId.set(r.assignmentId, v === null ? null : Number(v))
  }

  // 已提交学生集合（按 assignmentId 分组），用于计算逾期未提交人数
  const submittedStudentIdsByAssignmentId = new Map<string, Set<string>>()
  for (const r of submittedStudentRows) {
    let set = submittedStudentIdsByAssignmentId.get(r.assignmentId)
    if (!set) {
      set = new Set<string>()
      submittedStudentIdsByAssignmentId.set(r.assignmentId, set)
    }
    set.add(r.studentId)
  }

  // 逾期未提交人数 = 目标学生数 - 已提交学生数（仅当 dueAt 已过时计算）
  const computeOverdueCount = (assignmentId: string, dueAt: Date | null): number => {
    if (!dueAt || dueAt > now) return 0
    const targetCount = targetCountByAssignmentId.get(assignmentId) ?? 0
    const submittedCount = submittedStudentIdsByAssignmentId.get(assignmentId)?.size ?? 0
    return Math.max(0, targetCount - submittedCount)
  }

  return data.map((a) => {
    const targetCount = targetCountByAssignmentId.get(a.id) ?? 0
    const submittedCount = submittedCountByAssignmentId.get(a.id) ?? 0
    const gradedCount = gradedCountByAssignmentId.get(a.id) ?? 0
    const averageScore = avgScoreByAssignmentId.get(a.id) ?? null
    const overdueCount = computeOverdueCount(a.id, a.dueAt)
    const item: HomeworkAssignmentListItem = {
      id: a.id,
      sourceExamId: a.sourceExamId,
      sourceExamTitle: a.sourceExam?.title ?? null,
      title: a.title,
      status: toHomeworkAssignmentStatus(a.status),
      availableAt: a.availableAt ? a.availableAt.toISOString() : null,
      dueAt: a.dueAt ? a.dueAt.toISOString() : null,
      allowLate: a.allowLate,
      lateDueAt: a.lateDueAt ? a.lateDueAt.toISOString() : null,
      maxAttempts: a.maxAttempts,
      createdAt: a.createdAt.toISOString(),
      updatedAt: a.updatedAt.toISOString(),
      targetCount,
      submittedCount,
      gradedCount,
      averageScore,
      overdueCount,
    }
    return item
  })
})

export const getHomeworkAssignmentReviewList = cache(async (params: { creatorId: string; scope?: DataScope }) => {
  const creatorId = params.creatorId.trim()
  if (!creatorId) return []

  const conditions = [eq(homeworkAssignments.creatorId, creatorId)]

  // Data scope filtering
  if (params.scope) {
    if (params.scope.type === "owned") {
      // Already filtered by creatorId above
    }
    if (params.scope.type === "class_taught" && params.scope.classIds.length > 0) {
      const classStudentIds = await getStudentIdsByClassIds(params.scope.classIds)

      const targetAssignmentIds = await db
        .selectDistinct({ assignmentId: homeworkAssignmentTargets.assignmentId })
        .from(homeworkAssignmentTargets)
        .where(inArray(homeworkAssignmentTargets.studentId, classStudentIds))

      conditions.push(inArray(homeworkAssignments.id, targetAssignmentIds.map((t) => t.assignmentId)))
    }
    if (params.scope.type === "grade_managed" && params.scope.gradeIds.length > 0) {
      const gradeExamIds = await getExamIdsByGradeIds(params.scope.gradeIds)

      conditions.push(inArray(homeworkAssignments.sourceExamId, gradeExamIds))
    }
  }

  const assignments = await db.query.homeworkAssignments.findMany({
    where: and(...conditions),
    orderBy: [desc(homeworkAssignments.createdAt)],
    with: { sourceExam: true },
  })

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

  const assignmentIds = assignments.map((a) => a.id)

  const [targetCountRows, submittedCountRows, gradedCountRows] = await Promise.all([
    db
      .select({
        assignmentId: homeworkAssignmentTargets.assignmentId,
        targetCount: sql<number>`COUNT(*)`,
      })
      .from(homeworkAssignmentTargets)
      .where(inArray(homeworkAssignmentTargets.assignmentId, assignmentIds))
      .groupBy(homeworkAssignmentTargets.assignmentId),
    db
      .select({
        assignmentId: homeworkSubmissions.assignmentId,
        submittedCount: sql<number>`COUNT(DISTINCT ${homeworkSubmissions.studentId})`,
      })
      .from(homeworkSubmissions)
      .where(
        and(
          inArray(homeworkSubmissions.assignmentId, assignmentIds),
          inArray(homeworkSubmissions.status, ["submitted", "graded"])
        )
      )
      .groupBy(homeworkSubmissions.assignmentId),
    db
      .select({
        assignmentId: homeworkSubmissions.assignmentId,
        gradedCount: sql<number>`COUNT(DISTINCT ${homeworkSubmissions.studentId})`,
      })
      .from(homeworkSubmissions)
      .where(and(inArray(homeworkSubmissions.assignmentId, assignmentIds), eq(homeworkSubmissions.status, "graded")))
      .groupBy(homeworkSubmissions.assignmentId),
  ])

  const targetCountByAssignmentId = new Map<string, number>()
  for (const r of targetCountRows) targetCountByAssignmentId.set(r.assignmentId, Number(r.targetCount ?? 0))

  const submittedCountByAssignmentId = new Map<string, number>()
  for (const r of submittedCountRows) submittedCountByAssignmentId.set(r.assignmentId, Number(r.submittedCount ?? 0))

  const gradedCountByAssignmentId = new Map<string, number>()
  for (const r of gradedCountRows) gradedCountByAssignmentId.set(r.assignmentId, Number(r.gradedCount ?? 0))

  return assignments.map((a) => {
    const item: HomeworkAssignmentReviewListItem = {
      id: a.id,
      title: a.title,
      status: toHomeworkAssignmentStatus(a.status),
      sourceExamTitle: a.sourceExam?.title ?? null,
      dueAt: a.dueAt ? a.dueAt.toISOString() : null,
      targetCount: targetCountByAssignmentId.get(a.id) ?? 0,
      submittedCount: submittedCountByAssignmentId.get(a.id) ?? 0,
      gradedCount: gradedCountByAssignmentId.get(a.id) ?? 0,
      createdAt: a.createdAt.toISOString(),
    }
    return item
  })
})

export const getHomeworkSubmissions = cache(async (params?: { assignmentId?: string; classId?: string; creatorId?: string; scope?: DataScope }) => {
  const conditions = []
  if (params?.assignmentId) conditions.push(eq(homeworkSubmissions.assignmentId, params.assignmentId))
  if (params?.classId) {
    const classStudentIds = await getStudentIdsByClassId(params.classId)

    const targetAssignmentIds = await db
      .selectDistinct({ assignmentId: homeworkAssignmentTargets.assignmentId })
      .from(homeworkAssignmentTargets)
      .where(inArray(homeworkAssignmentTargets.studentId, classStudentIds))

    conditions.push(inArray(homeworkSubmissions.studentId, classStudentIds))
    conditions.push(inArray(homeworkSubmissions.assignmentId, targetAssignmentIds.map((t) => t.assignmentId)))
  }
  if (params?.creatorId) {
    const creatorAssignmentIds = db
      .select({ assignmentId: homeworkAssignments.id })
      .from(homeworkAssignments)
      .where(eq(homeworkAssignments.creatorId, params.creatorId))

    conditions.push(inArray(homeworkSubmissions.assignmentId, creatorAssignmentIds))
  }

  // Data scope filtering
  if (params?.scope) {
    if (params.scope.type === "owned") {
      const creatorAssignmentIds = db
        .select({ assignmentId: homeworkAssignments.id })
        .from(homeworkAssignments)
        .where(eq(homeworkAssignments.creatorId, params.scope.userId))

      conditions.push(inArray(homeworkSubmissions.assignmentId, creatorAssignmentIds))
    }
    if (params.scope.type === "class_taught" && params.scope.classIds.length > 0) {
      const classStudentIds = await getStudentIdsByClassIds(params.scope.classIds)

      conditions.push(inArray(homeworkSubmissions.studentId, classStudentIds))
    }
    if (params.scope.type === "grade_managed" && params.scope.gradeIds.length > 0) {
      const gradeExamIds = await getExamIdsByGradeIds(params.scope.gradeIds)

      const gradeAssignmentIds = db
        .select({ assignmentId: homeworkAssignments.id })
        .from(homeworkAssignments)
        .where(inArray(homeworkAssignments.sourceExamId, gradeExamIds))

      conditions.push(inArray(homeworkSubmissions.assignmentId, gradeAssignmentIds))
    }
  }

  const data = await db.query.homeworkSubmissions.findMany({
    where: conditions.length ? and(...conditions) : undefined,
    orderBy: [desc(homeworkSubmissions.updatedAt)],
    with: {
      assignment: true,
      student: true,
    },
  })

  return data.map((s) => {
    const item: HomeworkSubmissionListItem = {
      id: s.id,
      assignmentId: s.assignmentId,
      assignmentTitle: s.assignment.title,
      studentName: s.student.name || "Unknown",
      submittedAt: s.submittedAt ? s.submittedAt.toISOString() : null,
      score: s.score ?? null,
      status: toHomeworkSubmissionStatus(s.status),
      isLate: s.isLate,
    }
    return item
  })
})

export const getHomeworkAssignmentById = cache(async (id: string, scope?: DataScope) => {
  const assignment = await db.query.homeworkAssignments.findFirst({
    where: eq(homeworkAssignments.id, id),
    with: {
      sourceExam: true,
    },
  })

  if (!assignment) return null

  // Data scope verification for single-item fetch
  if (scope && scope.type !== "all") {
    if (scope.type === "owned" && assignment.creatorId !== scope.userId) {
      return null
    }
    if (scope.type === "grade_managed" && scope.gradeIds.length > 0) {
      // 快速作业（无 sourceExamId）不归年级主任管辖，直接拒绝
      if (!assignment.sourceExamId) return null
      const examIds = await getExamIdsByGradeIds(scope.gradeIds)
      if (!examIds.includes(assignment.sourceExamId)) {
        return null
      }
    }
    if (scope.type === "class_taught" && scope.classIds.length > 0) {
      const studentIds = await getStudentIdsByClassIds(scope.classIds)
      if (studentIds.length > 0) {
        const target = await db.query.homeworkAssignmentTargets.findFirst({
          where: and(
            eq(homeworkAssignmentTargets.assignmentId, id),
            inArray(homeworkAssignmentTargets.studentId, studentIds)
          ),
        })
        if (!target) return null
      } else {
        return null
      }
    }
  }

  const [targetsRows, submissionsRows, submittedRows, gradedRows] = await Promise.all([
    db
      .select({ c: count() })
      .from(homeworkAssignmentTargets)
      .where(eq(homeworkAssignmentTargets.assignmentId, id)),
    db
      .select({ c: count() })
      .from(homeworkSubmissions)
      .where(eq(homeworkSubmissions.assignmentId, id)),
    db
      .select({ c: sql<number>`COUNT(DISTINCT ${homeworkSubmissions.studentId})` })
      .from(homeworkSubmissions)
      .where(
        and(eq(homeworkSubmissions.assignmentId, id), inArray(homeworkSubmissions.status, ["submitted", "graded"]))
      ),
    db
      .select({ c: sql<number>`COUNT(DISTINCT ${homeworkSubmissions.studentId})` })
      .from(homeworkSubmissions)
      .where(and(eq(homeworkSubmissions.assignmentId, id), eq(homeworkSubmissions.status, "graded"))),
  ])

  return {
    id: assignment.id,
    title: assignment.title,
    description: assignment.description,
    status: toHomeworkAssignmentStatus(assignment.status),
    sourceExamId: assignment.sourceExamId,
    sourceExamTitle: assignment.sourceExam?.title ?? null,
    structure: assignment.structure,
    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,
    targetCount: targetsRows[0]?.c ?? 0,
    submissionCount: submissionsRows[0]?.c ?? 0,
    submittedCount: submittedRows[0]?.c ?? 0,
    gradedCount: gradedRows[0]?.c ?? 0,
    createdAt: assignment.createdAt.toISOString(),
    updatedAt: assignment.updatedAt.toISOString(),
  }
})

export const getHomeworkSubmissionDetails = cache(async (submissionId: string): Promise<HomeworkSubmissionDetails | null> => {
  const submission = await db.query.homeworkSubmissions.findFirst({
    where: eq(homeworkSubmissions.id, submissionId),
    with: {
      student: true,
      assignment: true,
    },
  })

  if (!submission) return null

  const [answers, assignmentQ] = await Promise.all([
    db.query.homeworkAnswers.findMany({
      where: eq(homeworkAnswers.submissionId, submissionId),
      with: {
        question: true,
      },
    }),
    db.query.homeworkAssignmentQuestions.findMany({
      where: eq(homeworkAssignmentQuestions.assignmentId, submission.assignmentId),
      orderBy: [desc(homeworkAssignmentQuestions.order)],
    }),
  ])

  const answersWithDetails = answers
    .map((ans) => {
      const aqRel = assignmentQ.find((q) => q.questionId === ans.questionId)
      return {
        id: ans.id,
        questionId: ans.questionId,
        questionContent: toQuestionContent(ans.question.content),
        questionType: ans.question.type,
        maxScore: aqRel?.score || 0,
        studentAnswer: ans.answerContent,
        score: ans.score,
        feedback: ans.feedback,
        order: aqRel?.order || 0,
      }
    })
    .sort((a, b) => a.order - b.order)

  // P1-8: Optimize adjacent submission navigation using LIMIT 1 queries
  // instead of fetching all submission IDs for the assignment.
  // Original ordering is desc(updatedAt): "previous" = newer, "next" = older.
  const currentUpdatedAt = submission.updatedAt

  const [prevSubmission, nextSubmission] = await Promise.all([
    // Previous (newer): closest submission with updatedAt > current
    db.query.homeworkSubmissions.findFirst({
      where: and(
        eq(homeworkSubmissions.assignmentId, submission.assignmentId),
        gt(homeworkSubmissions.updatedAt, currentUpdatedAt)
      ),
      orderBy: [asc(homeworkSubmissions.updatedAt)],
      columns: { id: true },
    }),
    // Next (older): closest submission with updatedAt < current
    db.query.homeworkSubmissions.findFirst({
      where: and(
        eq(homeworkSubmissions.assignmentId, submission.assignmentId),
        lt(homeworkSubmissions.updatedAt, currentUpdatedAt)
      ),
      orderBy: [desc(homeworkSubmissions.updatedAt)],
      columns: { id: true },
    }),
  ])

  const prevSubmissionId = prevSubmission?.id ?? null
  const nextSubmissionId = nextSubmission?.id ?? null

  return {
    id: submission.id,
    assignmentId: submission.assignmentId,
    assignmentTitle: submission.assignment.title,
    studentName: submission.student.name || "Unknown",
    submittedAt: submission.submittedAt ? submission.submittedAt.toISOString() : null,
    status: toHomeworkSubmissionStatus(submission.status),
    totalScore: submission.score,
    answers: answersWithDetails,
    prevSubmissionId,
    nextSubmissionId,
  }
})

/**
 * 查询某作业下的优秀提交（P3-1：优秀作业展示）。
 *
 * 评分规则：
 * - 仅返回 `status = "graded"` 且 `score IS NOT NULL` 的提交。
 * - 同一学生多次提交时，仅保留最高分（避免重复展示）。
 * - 按得分百分比 `score / maxScore` 降序排列。
 * - 过滤出百分比 ≥ `minPercentage`（默认 80）的提交。
 *
 * 权限说明：调用方必须在外层通过 `requirePermission()` 校验，
 * 并通过 `scope` 参数传入数据范围（教师仅可见自己班级的学生提交）。
 */
export const getExcellentSubmissions = cache(async (params: {
  assignmentId: string
  minPercentage?: number
  limit?: number
  scope?: DataScope
}): Promise<ExcellentSubmissionItem[]> => {
  const minPct = params.minPercentage ?? 80
  const limit = Math.max(1, Math.min(50, params.limit ?? 10))

  // 1. 拉取该作业所有已批改提交
  const conditions = [
    eq(homeworkSubmissions.assignmentId, params.assignmentId),
    eq(homeworkSubmissions.status, "graded"),
    sql`${homeworkSubmissions.score} IS NOT NULL`,
  ]

  if (params.scope) {
    if (params.scope.type === "class_taught" && params.scope.classIds.length > 0) {
      const classStudentIds = await getStudentIdsByClassIds(params.scope.classIds)
      conditions.push(inArray(homeworkSubmissions.studentId, classStudentIds))
    } else if (params.scope.type === "owned") {
      const creatorAssignmentIds = db
        .select({ assignmentId: homeworkAssignments.id })
        .from(homeworkAssignments)
        .where(eq(homeworkAssignments.creatorId, params.scope.userId))

      conditions.push(inArray(homeworkSubmissions.assignmentId, creatorAssignmentIds))
    }
    // grade_managed / all 不额外过滤（依赖 assignment 维度即可）
  }

  const submissions = await db.query.homeworkSubmissions.findMany({
    where: and(...conditions),
    with: {
      student: true,
      assignment: true,
    },
  })

  // 2. 计算总分阈值（来自作业题目分数之和）
  const maxScoreRows = await db
    .select({
      maxScore: sql<number>`COALESCE(SUM(${homeworkAssignmentQuestions.score}), 0)`,
    })
    .from(homeworkAssignmentQuestions)
    .where(eq(homeworkAssignmentQuestions.assignmentId, params.assignmentId))

  const maxScore = Number(maxScoreRows[0]?.maxScore ?? 0)

  // 3. 同一学生取最高分
  const bestByStudent = new Map<string, ExcellentSubmissionItem>()
  for (const s of submissions) {
    if (s.score === null) continue
    const percentage = maxScore > 0 ? Math.round((s.score / maxScore) * 1000) / 10 : 0
    if (percentage < minPct) continue

    const existing = bestByStudent.get(s.studentId)
    if (existing && existing.percentage >= percentage) continue

    bestByStudent.set(s.studentId, {
      submissionId: s.id,
      assignmentId: s.assignmentId,
      assignmentTitle: s.assignment.title,
      studentName: s.student.name || "Unknown",
      totalScore: s.score,
      maxScore,
      percentage,
      submittedAt: s.submittedAt ? s.submittedAt.toISOString() : "",
      isLate: s.isLate,
    })
  }

  // 4. 排序 + 截断
  return Array.from(bestByStudent.values())
    .sort((a, b) => b.percentage - a.percentage)
    .slice(0, limit)
})

/**
 * 查询某作业下尚未提交（或未开始）的学生列表（P3-2：作业催交提醒）。
 *
 * 逻辑：
 * - 从 `homeworkAssignmentTargets` 获取作业目标学生。
 * - 排除已有 `submitted` 或 `graded` 状态提交的学生。
 * - 返回学生 ID + 姓名，用于发送催交通知。
 *
 * 权限：调用方必须通过 `requirePermission()` 校验。
 */
export const getUnsubmittedStudents = cache(async (params: {
  assignmentId: string
  scope?: DataScope
}): Promise<Array<{ studentId: string; studentName: string }>> => {
  // 1. 获取作业目标学生
  const targets = await db.query.homeworkAssignmentTargets.findMany({
    where: eq(homeworkAssignmentTargets.assignmentId, params.assignmentId),
    with: {
      student: true,
    },
  })

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

  // 2. 获取已提交的学生 ID（submitted 或 graded 状态）
  const submitted = await db.query.homeworkSubmissions.findMany({
    where: and(
      eq(homeworkSubmissions.assignmentId, params.assignmentId),
      inArray(homeworkSubmissions.status, ["submitted", "graded"])
    ),
    columns: { studentId: true },
  })

  const submittedIds = new Set(submitted.map((s) => s.studentId))

  // 3. 过滤出未提交的学生
  const unsubmitted = targets
    .filter((t) => !submittedIds.has(t.studentId))
    .map((t) => ({
      studentId: t.studentId,
      studentName: t.student.name || "Unknown",
    }))

  return unsubmitted
})


