/**
 * Normalisation for integer score fields.
 *
 * Kept free of React so both the single grader and the bulk grading table share
 * one rule instead of two drifting copies. A grade that is clamped differently
 * depending on which screen the teacher used is a bug waiting to be reported.
 */

/**
 * Accept only a clean non-negative integer within `max`.
 *
 * The fields these back are `text` inputs rather than `number` because a number
 * input still accepts `e`, `+`, `-` and `.` — `1e2` is a valid number to the
 * browser — and reports an empty value for anything it deems malformed, so a
 * rejected keystroke is indistinguishable from a cleared field.
 *
 * Anything that is not already plain digits is *rejected*, never repaired. A
 * pasted `5.5` must not become `55`, and a pasted `1e2` must not become `12`:
 * silently turning one number into a different one is worse than doing nothing
 * in a field that decides a student's grade.
 *
 * Returns `null` to mean "reject this edit, keep what was there".
 */
export function normaliseInteger(raw: string, max: number): string | null {
  const trimmed = raw.trim();
  if (trimmed === "") return "";
  if (!/^\d+$/.test(trimmed)) return null;
  // Strip leading zeros but keep a lone "0" ("007" → "7").
  const digits = trimmed.replace(/^0+(?=\d)/, "");
  return Number(digits) > max ? null : digits;
}

/**
 * Characters a number input would have allowed but that make no sense for an
 * integer score. Blocking them on keydown stops the field flickering through an
 * invalid state that the change handler would then have to undo.
 */
export const BLOCKED_NUMERIC_KEYS = new Set(["e", "E", "+", "-", ".", ","]);

/**
 * Whether a raw score string is acceptable, treating `""` as "leave ungraded".
 *
 * Mirrors `normaliseInteger` — same digit-only rule, same ceiling — so the
 * submit button is never enabled for a value the field itself would refuse.
 */
export function isValidScoreInput(raw: string, max: number): boolean {
  const trimmed = raw.trim();
  if (trimmed === "") return true;
  return /^\d+$/.test(trimmed) && Number(trimmed) <= max;
}
