"""mark_correction — canonical writer for CorrectionEntry (Rule 10).

Records that a student has completed a correction on a graded submission.
Append-only (Rule 9): creates a new row, never edits or deletes.
Idempotent per (student, submission, same calendar day) to prevent accidental
double-tap duplicates from the UI.

Standards: Bloom 1968 (parallel second assessment); Guskey 1997;
NCTQ Correctives Indicator; Rule 9, Rule 10, Rule 14, Rule 26;
ISO 27001 A.8.15 (append-only audit).
"""
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from exams.models import Student, Submission, CorrectionEntry


class Command(BaseCommand):
    help = "Record a student's correction of a graded Submission (append-only)."

    def add_arguments(self, p):
        p.add_argument("--student", type=str, required=True)
        p.add_argument("--submission", type=int, required=True)
        p.add_argument("--note", type=str, default="")

    def handle(self, *args, **options):
        code = options["student"].strip().upper()
        sub_id = options["submission"]
        note = (options["note"] or "").strip()[:200]

        try:
            student = Student.objects.get(code=code)
        except Student.DoesNotExist:
            raise CommandError("student not found: " + code)
        try:
            sub = Submission.objects.get(id=sub_id)
        except Submission.DoesNotExist:
            raise CommandError("submission not found: %d" % sub_id)

        # Rule 14: submission's Exam.student must match.
        if sub.exam.student_id != student.id:
            raise CommandError("submission %d does not belong to %s" % (sub_id, code))

        # Idempotent per calendar day (UI double-tap tolerance).
        today = date.today()
        existing = CorrectionEntry.objects.filter(
            student=student, submission=sub,
            marked_at__date=today).first()
        if existing:
            self.stdout.write("already recorded today: correction#%d" % existing.id)
            return

        with transaction.atomic():
            entry = CorrectionEntry.objects.create(
                student=student, submission=sub, note=note)
        self.stdout.write("recorded correction#%d for %s on submission %d"
                          % (entry.id, student.code, sub_id))
