import "server-only";
import { prisma } from "@/lib/db";
import type { QuestionType, Role } from "@prisma/client";
import { seededShuffle, secondsRemaining, attemptsRemaining } from "@/lib/quiz";

/**
 * Quiz reads.
 *
 * The single most important rule in this file: a quiz's answer key must never
 * reach a student's browser before they submit. `correctAnswer` and
 * `explanation` therefore live only on the staff and post-submission shapes,
 * and the student-facing question type does not declare them at all. Splitting
 * the types is what makes that enforceable rather than merely intended.
 */

export interface QuizScope {
  userId: string;
  role: Role;
}

/** A question as a student sees it while answering — no key, no explanation. */
export interface StudentQuestion {
  id: string;
  prompt: string;
  type: QuestionType;
  /** Empty for SHORT_ANSWER, which has no options to choose from. */
  options: string[];
  points: number;
  orderIndex: number;
}

/** A question after marking, with everything revealed. */
export interface ReviewedQuestion extends StudentQuestion {
  correctAnswer: unknown;
  explanation: string | null;
  /** What this student answered, if anything. */
  response: unknown;
  isCorrect: boolean;
  pointsAwarded: number;
  /**
   * Row id of the stored answer, needed to mark a CODE question by hand.
   * Null when the student left the question blank.
   */
  answerId: string | null;
}

export interface AttemptSummary {
  id: string;
  attemptNo: number;
  startedAt: Date;
  submittedAt: Date | null;
  /** Percentage, 0–100. */
  score: number;
  maxScore: number;
  passed: boolean;
}

export interface QuizAccess {
  /** The student may start (or resume) an attempt now. */
  canAttempt: boolean;
  /** Why not, when `canAttempt` is false. */
  reason: string | null;
  attemptsUsed: number;
  attemptsLeft: number;
}

export interface StudentQuiz {
  quizId: string;
  assignmentId: string;
  assignmentTitle: string;
  courseId: string;
  courseTitle: string;
  instructions: string | null;
  dueAt: Date | null;
  passingScore: number;
  timeLimitMinutes: number | null;
  shuffleQuestions: boolean;
  allowRetakes: boolean;
  maxAttempts: number;
  maxScore: number;
  questionCount: number;
  /** Null when no attempt is in progress. */
  activeAttemptId: string | null;
  attempts: AttemptSummary[];
  access: QuizAccess;
  /** Highest percentage across submitted attempts, or null. */
  bestScore: number | null;
}

/**
 * Prisma fragment: assignments the actor may read.
 *
 * Mirrors `assignmentAccessFilter` in `queries/assignments.ts` so a quiz is
 * visible exactly when its assignment is.
 */
function assignmentAccessFilter(scope: QuizScope) {
  if (scope.role === "ADMIN") return {};
  if (scope.role === "TEACHER") {
    return {
      course: {
        OR: [{ teacherId: scope.userId }, { classroom: { teacherId: scope.userId } }],
      },
    };
  }
  return {
    status: "PUBLISHED" as const,
    course: {
      OR: [
        { enrollments: { some: { studentId: scope.userId } } },
        {
          classroom: {
            enrollments: { some: { studentId: scope.userId, status: "ACTIVE" as const } },
          },
        },
      ],
    },
  };
}

function toStringArray(value: unknown): string[] {
  if (!Array.isArray(value)) return [];
  return value.filter((entry): entry is string => typeof entry === "string");
}

const QUESTION_SELECT = {
  id: true,
  prompt: true,
  type: true,
  options: true,
  points: true,
  orderIndex: true,
} as const;

/**
 * Everything a student needs before starting, plus their attempt history.
 *
 * Returns null when the quiz does not exist or the student may not see it, so
 * callers can `notFound()` without distinguishing the two.
 */
export async function getStudentQuiz(
  scope: QuizScope,
  assignmentId: string
): Promise<StudentQuiz | null> {
  const assignment = await prisma.assignment.findFirst({
    where: { id: assignmentId, type: "QUIZ", AND: [assignmentAccessFilter(scope)] },
    select: {
      id: true,
      title: true,
      instructions: true,
      dueAt: true,
      allowLate: true,
      maxScore: true,
      status: true,
      courseId: true,
      course: { select: { title: true } },
      quiz: {
        select: {
          id: true,
          passingScore: true,
          timeLimitMinutes: true,
          shuffleQuestions: true,
          allowRetakes: true,
          maxAttempts: true,
          _count: { select: { questions: true } },
          attempts: {
            where: { studentId: scope.userId },
            orderBy: { attemptNo: "asc" },
            select: {
              id: true,
              attemptNo: true,
              startedAt: true,
              submittedAt: true,
              score: true,
              maxScore: true,
              passed: true,
            },
          },
        },
      },
    },
  });

  if (!assignment?.quiz) return null;
  const quiz = assignment.quiz;

  const attempts = quiz.attempts;
  const submitted = attempts.filter((attempt) => attempt.submittedAt !== null);
  const inProgress = attempts.find((attempt) => attempt.submittedAt === null) ?? null;

  const left = attemptsRemaining(quiz.maxAttempts, quiz.allowRetakes, submitted.length);

  // Reasons are ordered by what the student can act on: an unfinished attempt
  // is resumable, so it is reported before the more final obstacles.
  let reason: string | null = null;
  if (quiz._count.questions === 0) {
    reason = "Kuis ini belum memiliki soal.";
  } else if (assignment.status !== "PUBLISHED") {
    reason = "Kuis ini belum dibuka.";
  } else if (inProgress) {
    reason = "Kamu masih punya percobaan yang belum dikumpulkan.";
  } else if (left <= 0) {
    reason = quiz.allowRetakes
      ? `Kesempatan mengerjakan sudah habis (${quiz.maxAttempts} percobaan).`
      : "Kuis ini hanya dapat dikerjakan satu kali.";
  } else if (assignment.dueAt && new Date() > assignment.dueAt && !assignment.allowLate) {
    reason = "Tenggat sudah lewat.";
  }

  const bestScore =
    submitted.length === 0 ? null : Math.max(...submitted.map((attempt) => attempt.score));

  return {
    quizId: quiz.id,
    assignmentId: assignment.id,
    assignmentTitle: assignment.title,
    courseId: assignment.courseId,
    courseTitle: assignment.course.title,
    instructions: assignment.instructions,
    dueAt: assignment.dueAt,
    passingScore: quiz.passingScore,
    timeLimitMinutes: quiz.timeLimitMinutes,
    shuffleQuestions: quiz.shuffleQuestions,
    allowRetakes: quiz.allowRetakes,
    maxAttempts: quiz.maxAttempts,
    maxScore: assignment.maxScore,
    questionCount: quiz._count.questions,
    activeAttemptId: inProgress?.id ?? null,
    attempts: submitted.map((attempt) => ({
      id: attempt.id,
      attemptNo: attempt.attemptNo,
      startedAt: attempt.startedAt,
      submittedAt: attempt.submittedAt,
      score: attempt.score,
      maxScore: attempt.maxScore,
      passed: attempt.passed,
    })),
    access: {
      canAttempt: reason === null,
      reason,
      attemptsUsed: submitted.length,
      attemptsLeft: left,
    },
    bestScore,
  };
}

export interface ActiveAttempt {
  attemptId: string;
  quizId: string;
  assignmentId: string;
  assignmentTitle: string;
  courseTitle: string;
  passingScore: number;
  maxScore: number;
  timeLimitMinutes: number | null;
  startedAt: Date;
  /** Seconds left, or null when untimed. */
  secondsRemaining: number | null;
  attemptNo: number;
  questions: StudentQuestion[];
}

/**
 * The paper a student is currently sitting.
 *
 * Only an attempt the caller owns and has not yet submitted can be loaded —
 * that single check is what stops one student from opening another's attempt,
 * or from reopening a paper whose answers are already marked.
 */
export async function getActiveAttempt(
  scope: QuizScope,
  attemptId: string
): Promise<ActiveAttempt | null> {
  const attempt = await prisma.quizAttempt.findFirst({
    where: { id: attemptId, studentId: scope.userId, submittedAt: null },
    select: {
      id: true,
      attemptNo: true,
      startedAt: true,
      quiz: {
        select: {
          id: true,
          passingScore: true,
          timeLimitMinutes: true,
          shuffleQuestions: true,
          questions: { select: QUESTION_SELECT, orderBy: { orderIndex: "asc" } },
          assignment: {
            select: {
              id: true,
              title: true,
              maxScore: true,
              status: true,
              course: { select: { title: true } },
            },
          },
        },
      },
    },
  });

  if (!attempt) return null;

  const { quiz } = attempt;
  const base: StudentQuestion[] = quiz.questions.map((question) => ({
    id: question.id,
    prompt: question.prompt,
    type: question.type,
    options: toStringArray(question.options),
    points: question.points,
    orderIndex: question.orderIndex,
  }));

  // Order is derived from the attempt id, so a reload shows the same paper
  // instead of renumbering it under the student's answers.
  const questions = quiz.shuffleQuestions ? seededShuffle(base, attempt.id) : base;

  return {
    attemptId: attempt.id,
    quizId: quiz.id,
    assignmentId: quiz.assignment.id,
    assignmentTitle: quiz.assignment.title,
    courseTitle: quiz.assignment.course.title,
    passingScore: quiz.passingScore,
    maxScore: quiz.assignment.maxScore,
    timeLimitMinutes: quiz.timeLimitMinutes,
    startedAt: attempt.startedAt,
    secondsRemaining: secondsRemaining(attempt.startedAt, quiz.timeLimitMinutes),
    attemptNo: attempt.attemptNo,
    questions,
  };
}

export interface AttemptResult {
  attemptId: string;
  quizId: string;
  assignmentId: string;
  assignmentTitle: string;
  courseId: string;
  courseTitle: string;
  attemptNo: number;
  startedAt: Date;
  submittedAt: Date;
  /** Percentage, 0–100. */
  score: number;
  /** Total points the quiz's questions are worth — not the assignment's maximum. */
  maxScore: number;
  /**
   * The assignment's own maximum, which is what the gradebook stores against.
   * A quiz's question points need not add up to it, so scaling the percentage
   * by `maxScore` above would report a grade the gradebook never held.
   */
  assignmentMaxScore: number;
  passingScore: number;
  passed: boolean;
  /** Points earned out of the points available. */
  pointsEarned: number;
  pointsPossible: number;
  /**
   * True when the quiz contains questions a machine cannot mark, so a teacher
   * has something to do here. This is a property of the quiz, not of the
   * attempt — it stays true after the marking is finished.
   */
  hasManualQuestions: boolean;
  /**
   * True when this student's grade is not final yet.
   *
   * Read from the submission rather than from the question types: a code
   * question that has been marked is still a code question, but the score is
   * no longer going to change. Checking the type alone left the student
   * reading "your score may still change" on a paper that was fully marked.
   */
  awaitingGrade: boolean;
  questions: ReviewedQuestion[];
}

/**
 * A marked paper. Staff may read any attempt; a student only their own, and
 * only once it has been submitted.
 */
export async function getAttemptResult(
  scope: QuizScope,
  attemptId: string
): Promise<AttemptResult | null> {
  const isStaff = scope.role === "ADMIN" || scope.role === "TEACHER";

  const attempt = await prisma.quizAttempt.findFirst({
    where: {
      id: attemptId,
      submittedAt: { not: null },
      ...(isStaff ? {} : { studentId: scope.userId }),
      ...(isStaff ? { quiz: { assignment: assignmentAccessFilter(scope) } } : {}),
    },
    select: {
      id: true,
      attemptNo: true,
      studentId: true,
      startedAt: true,
      submittedAt: true,
      score: true,
      maxScore: true,
      passed: true,
      quiz: {
        select: {
          id: true,
          passingScore: true,
          assignment: {
            select: {
              id: true,
              title: true,
              maxScore: true,
              courseId: true,
              course: { select: { title: true } },
            },
          },
          questions: { select: QUESTION_SELECT, orderBy: { orderIndex: "asc" } },
        },
      },
      answers: {
        select: {
          id: true,
          questionId: true,
          response: true,
          isCorrect: true,
          pointsAwarded: true,
        },
      },
    },
  });

  if (!attempt || !attempt.submittedAt) return null;

  const byQuestion = new Map(attempt.answers.map((answer) => [answer.questionId, answer]));
  const quizQuestions = await prisma.quizQuestion.findMany({
    where: { quizId: attempt.quiz.id },
    select: { id: true, correctAnswer: true, explanation: true },
  });
  const keyByQuestion = new Map(quizQuestions.map((question) => [question.id, question]));

  const questions: ReviewedQuestion[] = attempt.quiz.questions.map((question) => {
    const key = keyByQuestion.get(question.id);
    const answer = byQuestion.get(question.id);
    return {
      id: question.id,
      prompt: question.prompt,
      type: question.type,
      options: toStringArray(question.options),
      points: question.points,
      orderIndex: question.orderIndex,
      correctAnswer: key?.correctAnswer ?? null,
      explanation: key?.explanation ?? null,
      response: answer?.response ?? null,
      isCorrect: answer?.isCorrect ?? false,
      pointsAwarded: answer?.pointsAwarded ?? 0,
      answerId: answer?.id ?? null,
    };
  });

  const pointsEarned = questions.reduce((sum, question) => sum + question.pointsAwarded, 0);
  const pointsPossible = questions.reduce((sum, question) => sum + question.points, 0);
  // A CODE question is never scored by machine, so its presence alone means a
  // human may still have to look at this attempt.
  const hasManualQuestions = questions.some((question) => question.type === "CODE");

  // Whether the grade is still in motion is a separate question, and only the
  // submission knows: it is set to SUBMITTED while any answer is unmarked and
  // to GRADED once the last one is written.
  const submission = await prisma.submission.findUnique({
    where: {
      assignmentId_studentId: {
        assignmentId: attempt.quiz.assignment.id,
        studentId: attempt.studentId,
      },
    },
    select: { status: true },
  });
  const awaitingGrade =
    submission !== null && (submission.status === "SUBMITTED" || submission.status === "LATE");

  return {
    attemptId: attempt.id,
    quizId: attempt.quiz.id,
    assignmentId: attempt.quiz.assignment.id,
    assignmentTitle: attempt.quiz.assignment.title,
    courseId: attempt.quiz.assignment.courseId,
    courseTitle: attempt.quiz.assignment.course.title,
    attemptNo: attempt.attemptNo,
    startedAt: attempt.startedAt,
    submittedAt: attempt.submittedAt,
    score: attempt.score,
    maxScore: attempt.maxScore,
    assignmentMaxScore: attempt.quiz.assignment.maxScore,
    passingScore: attempt.quiz.passingScore,
    passed: attempt.passed,
    pointsEarned,
    pointsPossible,
    hasManualQuestions,
    awaitingGrade,
    questions,
  };
}

// --- staff ------------------------------------------------------------------

/** A question as its author edits it — the answer key is included. */
export interface StaffQuestion {
  id: string;
  prompt: string;
  type: QuestionType;
  options: string[];
  correctAnswer: unknown;
  explanation: string | null;
  points: number;
  orderIndex: number;
  /**
   * How many students have answered it. A question with answers cannot be
   * deleted — the answers are graded records — so the editor locks it.
   */
  answeredCount: number;
}

export interface StaffQuiz {
  quizId: string;
  assignmentId: string;
  assignmentTitle: string;
  courseId: string;
  courseTitle: string;
  status: "DRAFT" | "PUBLISHED" | "ARCHIVED";
  passingScore: number;
  timeLimitMinutes: number | null;
  shuffleQuestions: boolean;
  allowRetakes: boolean;
  maxAttempts: number;
  maxScore: number;
  questions: StaffQuestion[];
}

/** The quiz behind an assignment, with its key, for the author or an admin. */
export async function getStaffQuiz(
  scope: QuizScope,
  assignmentId: string
): Promise<StaffQuiz | null> {
  const assignment = await prisma.assignment.findFirst({
    where: { id: assignmentId, AND: [assignmentAccessFilter(scope)] },
    select: {
      id: true,
      title: true,
      status: true,
      maxScore: true,
      courseId: true,
      course: { select: { title: true } },
      quiz: {
        select: {
          id: true,
          passingScore: true,
          timeLimitMinutes: true,
          shuffleQuestions: true,
          allowRetakes: true,
          maxAttempts: true,
          questions: {
            select: {
              id: true,
              prompt: true,
              type: true,
              options: true,
              correctAnswer: true,
              explanation: true,
              points: true,
              orderIndex: true,
              _count: { select: { answers: true } },
            },
            orderBy: { orderIndex: "asc" },
          },
        },
      },
    },
  });

  if (!assignment?.quiz) return null;
  const quiz = assignment.quiz;

  return {
    quizId: quiz.id,
    assignmentId: assignment.id,
    assignmentTitle: assignment.title,
    courseId: assignment.courseId,
    courseTitle: assignment.course.title,
    status: assignment.status,
    passingScore: quiz.passingScore,
    timeLimitMinutes: quiz.timeLimitMinutes,
    shuffleQuestions: quiz.shuffleQuestions,
    allowRetakes: quiz.allowRetakes,
    maxAttempts: quiz.maxAttempts,
    maxScore: assignment.maxScore,
    questions: quiz.questions.map((question) => ({
      id: question.id,
      prompt: question.prompt,
      type: question.type,
      options: toStringArray(question.options),
      correctAnswer: question.correctAnswer,
      explanation: question.explanation,
      points: question.points,
      orderIndex: question.orderIndex,
      answeredCount: question._count.answers,
    })),
  };
}

export interface QuizAttemptRow {
  id: string;
  attemptNo: number;
  studentId: string;
  studentName: string;
  username: string;
  startedAt: Date;
  submittedAt: Date | null;
  score: number;
  maxScore: number;
  passed: boolean;
  /** Null while the attempt is still open. */
  durationMinutes: number | null;
}

/** Every attempt on an assignment, newest first — the staff marking view. */
export async function listQuizAttempts(assignmentId: string): Promise<QuizAttemptRow[]> {
  const attempts = await prisma.quizAttempt.findMany({
    where: { quiz: { assignmentId } },
    orderBy: [{ submittedAt: "desc" }, { startedAt: "desc" }],
    select: {
      id: true,
      attemptNo: true,
      startedAt: true,
      submittedAt: true,
      score: true,
      maxScore: true,
      passed: true,
      studentId: true,
      student: { select: { fullName: true, username: true } },
    },
  });

  return attempts.map((attempt) => ({
    id: attempt.id,
    attemptNo: attempt.attemptNo,
    studentId: attempt.studentId,
    studentName: attempt.student.fullName,
    username: attempt.student.username,
    startedAt: attempt.startedAt,
    submittedAt: attempt.submittedAt,
    score: attempt.score,
    maxScore: attempt.maxScore,
    passed: attempt.passed,
    durationMinutes: attempt.submittedAt
      ? Math.max(
          1,
          Math.round(
            (attempt.submittedAt.getTime() - attempt.startedAt.getTime()) / (60 * 1000)
          )
        )
      : null,
  }));
}

export interface QuestionStat {
  questionId: string;
  prompt: string;
  type: QuestionType;
  points: number;
  answered: number;
  correct: number;
  /** 0–100. */
  correctRate: number;
}

export interface QuizStats {
  submittedAttempts: number;
  openAttempts: number;
  uniqueStudents: number;
  averageScore: number | null;
  passRate: number | null;
  questions: QuestionStat[];
}

/**
 * Per-question difficulty for one quiz.
 *
 * `correctRate` is the number that matters to a teacher: a question most of the
 * class fails is usually a badly worded question, not a badly taught topic.
 */
export async function getQuizStats(assignmentId: string): Promise<QuizStats | null> {
  const quiz = await prisma.quiz.findUnique({
    where: { assignmentId },
    select: {
      id: true,
      questions: {
        select: {
          id: true,
          prompt: true,
          type: true,
          points: true,
          orderIndex: true,
          answers: { select: { isCorrect: true } },
        },
        orderBy: { orderIndex: "asc" },
      },
      attempts: {
        select: { id: true, studentId: true, submittedAt: true, score: true, passed: true },
      },
    },
  });

  if (!quiz) return null;

  const submitted = quiz.attempts.filter((attempt) => attempt.submittedAt !== null);
  const scores = submitted.map((attempt) => attempt.score);
  const passed = submitted.filter((attempt) => attempt.passed).length;

  return {
    submittedAttempts: submitted.length,
    openAttempts: quiz.attempts.length - submitted.length,
    uniqueStudents: new Set(quiz.attempts.map((attempt) => attempt.studentId)).size,
    averageScore:
      scores.length === 0 ? null : Math.round(scores.reduce((a, b) => a + b, 0) / scores.length),
    passRate: submitted.length === 0 ? null : Math.round((passed / submitted.length) * 100),
    questions: quiz.questions.map((question) => {
      const answered = question.answers.length;
      const correct = question.answers.filter((answer) => answer.isCorrect).length;
      return {
        questionId: question.id,
        prompt: question.prompt,
        type: question.type,
        points: question.points,
        answered,
        correct,
        correctRate: answered === 0 ? 0 : Math.round((correct / answered) * 100),
      };
    }),
  };
}
