"""reconcile_task_categories - align StudentTask.category with Rule 14.

MANAGEMENT set per migration 0039 docstring:
  BOOK_INGEST, KC_TAG, KC_DISCOVERY, KC_MISCONCEPTION,
  KC_SOCRATIC_LADDER, GLOSSARY, STORY
ACADEMIC set:
  HANDWRITING_EN, HANDWRITING_UR, READING_EN, READING_UR

Any row whose category does not match its task_type is corrected.
Append-only discipline: this is a data correction, not a delete
(migration 0039 does the same; Rule 9 forbids deletes, not fixes).

Standards: Rule 14 (task categories); Rule 26 (standards above directive);
AERA/APA/NCME 2014 Std 1.0 (each section names its construct);
ISO 21001:2018; COBIT 2019.
"""
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from exams.models import StudentTask

MANAGEMENT_TYPES = ["BOOK_INGEST", "KC_TAG", "KC_DISCOVERY",
                    "KC_MISCONCEPTION", "KC_SOCRATIC_LADDER",
                    "GLOSSARY", "STORY"]
ACADEMIC_TYPES = ["HANDWRITING_EN", "HANDWRITING_UR",
                  "READING_EN", "READING_UR"]


class Command(BaseCommand):
    help = "Align StudentTask.category with Rule 14 (migration 0039 intent)."
    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 + ")")
        to_mgmt = StudentTask.objects.filter(
            task_type__in=MANAGEMENT_TYPES).exclude(category="MANAGEMENT")
        to_acad = StudentTask.objects.filter(
            task_type__in=ACADEMIC_TYPES).exclude(category="ACADEMIC")
        n_mgmt = to_mgmt.count()
        n_acad = to_acad.count()
        self.stdout.write("rows to flip -> MANAGEMENT: " + str(n_mgmt))
        self.stdout.write("rows to flip -> ACADEMIC:   " + str(n_acad))
        if not o["apply"]:
            self.stdout.write("(DRY RUN - pass --apply to write)")
            return
        with transaction.atomic():
            a = to_mgmt.update(category="MANAGEMENT")
            b = to_acad.update(category="ACADEMIC")
        self.stdout.write("Applied: " + str(a) + " -> MANAGEMENT, "
                          + str(b) + " -> ACADEMIC.")
