"""reconcile_ur_book_refs v3 - final corrective close.

History:
  v1 (2026-10-08): created clean 2-page ASSIGNED refs across the full
    UR-9-BOOK range 197-260, unaware that the two students had already
    completed distinct halves (S-0005: 197-228; S-0008: 229-260).
  v2: marked exact-dup ASSIGNED rows SKIPPED; 14 SKIPPED, 18 left.
  v3 (this): marks ALL remaining open UR-9-BOOK rows SKIPPED.
    Reason: they are either own-dups or peer-dups of DONE work; both
    classes violate Rule 25 (MANAGEMENT exclusive per task_ref) and
    are noise under MTSS/NCII (per-student progress).

Correct end state:
  - 37 DONE rows (history, Rule 9)
  - 32 SKIPPED rows (v1 creation retired)
  - 0 open UR-9-BOOK rows

Standards: Rule 4 (verify); Rule 9 (mark, never delete);
Rule 14 (BOOK_INGEST = MANAGEMENT); Rule 25 (exclusive per task_ref);
Rule 26 (standards above directive - my v1 violated MTSS);
ISO 8000-61 (data quality); ISO 27001 A.8.15.
"""
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.utils import timezone
from exams.models import StudentTask


class Command(BaseCommand):
    help = "Final corrective: mark all open UR-9-BOOK rows SKIPPED."
    def add_arguments(self, p):
        p.add_argument("--apply", action="store_true")
        p.add_argument("--all-pipelines", action="store_true",
                       help="System-wide sweep. Requires --reason.")
        p.add_argument("--reason", default=None,
                       help="Justification for --all-pipelines (>=20 chars).")
    def handle(self, *a, **o):
        # Turn 5b-1 scope guard (design/ISOLATION-v1.0.md; Rule 28;
        # Saltzer & Schroeder 1975 - fail-safe default)
        if not o.get("all_pipelines"):
            raise CommandError(
                "Refused: this command is system-wide. "
                "Use --all-pipelines --reason '...' (>=20 chars)."
            )
        _reason = (o.get("reason") or "").strip()
        if len(_reason) < 20:
            raise CommandError(
                "--all-pipelines requires --reason with >= 20 chars."
            )
        self.stdout.write("SCOPE: ALL pipelines (reason=" + _reason + ")")
        open_qs = StudentTask.objects.filter(
            task_ref__startswith="UR-9-BOOK",
            status__in=["ASSIGNED", "IN_PROGRESS"])
        self.stdout.write("open UR-9-BOOK rows to SKIP: " + str(open_qs.count()))
        for t in open_qs.order_by("student__code", "task_ref")[:40]:
            self.stdout.write("  " + t.student.code + " " + t.task_ref)
        if not o["apply"]:
            self.stdout.write("(DRY RUN - pass --apply to write)")
            return
        now = timezone.now()
        with transaction.atomic():
            n = open_qs.update(
                status="SKIPPED", unassigned_at=now,
                notes="[reconcile_ur v3 2026-10-08] retired - work already DONE "
                      "(own or peer half); Rule 25 / MTSS; v1 reconciler created "
                      "in error")
        self.stdout.write("Applied: marked " + str(n) + " SKIPPED.")
