import "server-only";
import type { QuestionType } from "@prisma/client";

/**
 * Quiz grading.
 *
 * Marked `server-only` on purpose: this module reads the answer key, and the
 * import makes a build fail loudly if a Client Component ever pulls it in. A
 * student with the browser console open must never be able to read the correct
 * answers before submitting.
 *
 * Every function here is pure — the caller owns persistence.
 */

/** A stored question, reduced to what grading needs. */
export interface GradableQuestion {
  id: string;
  type: QuestionType;
  /** Index, or indices for MULTI_SELECT. */
  correctAnswer: unknown;
  points: number;
}

/** A student's answer, as it arrives from the form. */
export type QuizResponse = number | number[] | string | null;

export interface GradedAnswer {
  questionId: string;
  response: QuizResponse;
  isCorrect: boolean;
  pointsAwarded: number;
  /** False when the question type cannot be scored by machine. */
  autoGraded: boolean;
}

/** Question types a machine can score. `CODE` needs a human. */
const AUTO_GRADED: ReadonlySet<QuestionType> = new Set<QuestionType>([
  "MULTIPLE_CHOICE",
  "MULTI_SELECT",
  "TRUE_FALSE",
  "SHORT_ANSWER",
]);

export function isAutoGraded(type: QuestionType): boolean {
  return AUTO_GRADED.has(type);
}

/**
 * Normalise free text before comparing.
 *
 * A student who types "Abstraksi." or "  abstraksi " has the right answer; the
 * difference is typography, not understanding. Case, surrounding whitespace,
 * internal runs of whitespace, and trailing punctuation are all discarded.
 */
function normaliseText(value: string): string {
  return value
    .trim()
    .toLowerCase()
    .replace(/\s+/g, " ")
    .replace(/[.,;:!?]+$/, "");
}

/** Coerce whatever the form posted into the shape a question expects. */
function asIndex(value: unknown): number | null {
  if (typeof value === "number" && Number.isInteger(value) && value >= 0) return value;
  if (typeof value === "string" && /^\d+$/.test(value.trim())) return Number(value.trim());
  return null;
}

function asIndexList(value: unknown): number[] {
  if (Array.isArray(value)) {
    return value
      .map((entry) => asIndex(entry))
      .filter((entry): entry is number => entry !== null)
      .sort((a, b) => a - b);
  }
  // A single checkbox still submits one value, not a one-element array.
  const single = asIndex(value);
  return single === null ? [] : [single];
}

/** Accepted answers for a SHORT_ANSWER, which may be one string or several. */
function acceptedAnswers(correct: unknown): string[] {
  if (typeof correct === "string") return [normaliseText(correct)];
  if (Array.isArray(correct)) {
    return correct
      .filter((entry): entry is string => typeof entry === "string")
      .map((entry) => normaliseText(entry));
  }
  return [];
}

/**
 * Score one answer.
 *
 * Partial credit is deliberately not awarded for MULTI_SELECT: a set that is
 * missing a correct option and a set that adds a wrong one are both wrong, and
 * awarding fractions makes the final score hard for a student to reason about.
 */
export function gradeAnswer(question: GradableQuestion, response: QuizResponse): GradedAnswer {
  const base = { questionId: question.id, response };

  if (!isAutoGraded(question.type)) {
    return { ...base, isCorrect: false, pointsAwarded: 0, autoGraded: false };
  }

  let isCorrect = false;

  switch (question.type) {
    case "MULTIPLE_CHOICE":
    case "TRUE_FALSE": {
      const chosen = asIndex(response);
      const correct = asIndex(question.correctAnswer);
      isCorrect = chosen !== null && correct !== null && chosen === correct;
      break;
    }
    case "MULTI_SELECT": {
      const chosen = asIndexList(response);
      const correct = asIndexList(question.correctAnswer);
      isCorrect =
        correct.length > 0 &&
        chosen.length === correct.length &&
        chosen.every((value, index) => value === correct[index]);
      break;
    }
    case "SHORT_ANSWER": {
      const text = typeof response === "string" ? normaliseText(response) : "";
      isCorrect = text.length > 0 && acceptedAnswers(question.correctAnswer).includes(text);
      break;
    }
    default:
      isCorrect = false;
  }

  return { ...base, isCorrect, pointsAwarded: isCorrect ? question.points : 0, autoGraded: true };
}

export interface QuizScore {
  /** Sum of points awarded. */
  earned: number;
  /** Sum of points available. */
  possible: number;
  /** Whole-number percentage, 0–100. */
  percentage: number;
  passed: boolean;
  /** True when at least one question still needs a human to mark it. */
  needsManualGrading: boolean;
}

/** Total a student scored across a whole attempt. */
export function scoreAttempt(
  questions: readonly GradableQuestion[],
  answers: readonly GradedAnswer[],
  passingScore: number
): QuizScore {
  const byQuestion = new Map(answers.map((answer) => [answer.questionId, answer]));

  let earned = 0;
  let possible = 0;
  let needsManualGrading = false;

  for (const question of questions) {
    possible += question.points;
    const answer = byQuestion.get(question.id);
    if (!answer) continue;
    earned += answer.pointsAwarded;
    if (!answer.autoGraded) needsManualGrading = true;
  }

  const percentage = possible > 0 ? Math.round((earned / possible) * 100) : 0;

  return {
    earned,
    possible,
    percentage,
    // A quiz with an unmarked question is not a pass yet, however well the
    // machine-scored part went.
    passed: !needsManualGrading && percentage >= passingScore,
    needsManualGrading,
  };
}

/**
 * Scale a quiz percentage onto the assignment's own maximum.
 *
 * The gradebook stores one score per assignment on the assignment's scale, so a
 * quiz marked out of 100 has to be rescaled when the assignment is worth 20.
 */
export function scaleToMaxScore(percentage: number, maxScore: number): number {
  return Math.max(0, Math.min(maxScore, Math.round((percentage / 100) * maxScore)));
}

/** How many attempts a student has left, given the quiz's own limits. */
export function attemptsRemaining(
  maxAttempts: number,
  allowRetakes: boolean,
  usedAttempts: number
): number {
  if (!allowRetakes) return usedAttempts === 0 ? 1 : 0;
  return Math.max(0, maxAttempts - usedAttempts);
}

/**
 * Shuffle with a seeded generator.
 *
 * `shuffleQuestions` must produce the same order for the same attempt: a
 * re-render or a resumed attempt that reshuffled would renumber the options
 * underneath the student's answer and score it against the wrong choice.
 */
export function seededShuffle<T>(items: readonly T[], seed: string): T[] {
  const result = [...items];
  let state = 2166136261;
  for (let index = 0; index < seed.length; index += 1) {
    state ^= seed.charCodeAt(index);
    state = Math.imul(state, 16777619);
  }

  const next = (): number => {
    state ^= state << 13;
    state ^= state >>> 17;
    state ^= state << 5;
    return (state >>> 0) / 4294967296;
  };

  for (let index = result.length - 1; index > 0; index -= 1) {
    const swap = Math.floor(next() * (index + 1));
    [result[index], result[swap]] = [result[swap], result[index]];
  }

  return result;
}

/** When a timed attempt must be handed in, or null when untimed. */
export function deadlineFor(startedAt: Date, timeLimitMinutes: number | null): Date | null {
  if (!timeLimitMinutes || timeLimitMinutes <= 0) return null;
  return new Date(startedAt.getTime() + timeLimitMinutes * 60 * 1000);
}

/**
 * Strip a leading "Kuis:" from an assignment title for display.
 *
 * Authors usually name the assignment "Kuis: Dasar JavaScript", so prefixing
 * our own label produced "Kuis: Kuis: Dasar JavaScript". Removing the author's
 * prefix when we add one of our own keeps both spellings readable.
 */
export function quizDisplayTitle(title: string): string {
  return title.replace(/^\s*(kuis|quiz)\s*:\s*/i, "").trim() || title;
}

/** Seconds left on a timed attempt; null when untimed, 0 once expired. */
export function secondsRemaining(startedAt: Date, timeLimitMinutes: number | null, now = new Date()): number | null {
  const deadline = deadlineFor(startedAt, timeLimitMinutes);
  if (!deadline) return null;
  return Math.max(0, Math.floor((deadline.getTime() - now.getTime()) / 1000));
}
