"""check_task_invariants — scan StudentTask rows for category/subject drift.

Reports (does not fix). Read-only by design.

Invariants:
  INV-1  ACADEMIC  => pipeline is None
  INV-2  ACADEMIC  => task_type in {HANDWRITING_EN, HANDWRITING_UR,
                                    READING_EN, READING_UR}
  INV-3  MANAGEMENT => task_type in {BOOK_INGEST, KC_DISCOVERY, KC_TAG,
                                     KC_MISCONCEPTION, KC_SOCRATIC_LADDER,
                                     GLOSSARY, STORY}
  INV-4  task_ref subject prefix matches pipeline.paper_code prefix
         (the DEF-003 rule, enforced at the row level)

Standards:
  Rule K   System K Kaam isolation
  Rule 14  task categories stay pure
  ISO 8000-61  data must be fit for purpose
  NIST SP 800-53 CM-3  configuration change control
  ALCOA+ (MHRA 2018)  accurate, consistent
  Rule 28  standards supremacy

Usage:
  python manage.py check_task_invariants
  python manage.py check_task_invariants --json /tmp/inv.json
"""
import json
from collections import Counter
from pathlib import Path

from django.core.management.base import BaseCommand

from exams.models import StudentTask


ACADEMIC_TYPES = frozenset({
    "HANDWRITING_EN", "HANDWRITING_UR", "READING_EN", "READING_UR",
})
MANAGEMENT_TYPES = frozenset({
    "BOOK_INGEST", "KC_DISCOVERY", "KC_TAG", "KC_MISCONCEPTION",
    "KC_SOCRATIC_LADDER", "GLOSSARY", "STORY",
})

SUBJECT_PREFIXES = frozenset({
    "MT", "PH", "CH", "BI", "EN", "UR", "IS", "CS", "TQ",
})


def _ref_prefix(task_ref):
    """Return the subject prefix from a task_ref, or '' if none.

    BOOK refs:      'MT-9-BOOK#p=1-2'  -> 'MT'
    KC refs:        'C9-MT01-RADICALS' -> 'MT'
    Subject refs:   'IS-9'             -> 'IS'
    Handwriting:    'HW-EN-W41'        -> '' (not a subject-scoped task)
    """
    if not task_ref:
        return ""
    ref = task_ref.strip().upper()
    # BOOK_INGEST style
    if "#" in ref:
        ref = ref.split("#", 1)[0]
    parts = ref.split("-")
    if len(parts) >= 2:
        if parts[0] == "C9":
            # KC code: C9-MT01-... -> MT01 -> MT
            body = parts[1] if len(parts) > 1 else ""
            return body[:2]
        if parts[0] in SUBJECT_PREFIXES:
            return parts[0]
    return ""


class Command(BaseCommand):
    help = "Scan StudentTask rows for category / subject / pipeline drift. Read-only."

    def add_arguments(self, parser):
        parser.add_argument("--json", dest="json_out", default="",
                            help="Write findings to this JSON path.")
        parser.add_argument("--quiet", action="store_true",
                            help="Only print if there is a violation (cron mode).")

    def handle(self, *args, **options):
        violations = {
            "INV-1": [],
            "INV-2": [],
            "INV-3": [],
            "INV-4": [],
        }
        total = 0
        for t in StudentTask.objects.select_related("student", "pipeline").iterator():
            total += 1
            cat = (t.category or "").strip()
            tt = (t.task_type or "").strip()

            if cat == "ACADEMIC":
                if t.pipeline_id is not None:
                    violations["INV-1"].append({
                        "id": t.id, "student": t.student.code,
                        "task_type": tt, "task_ref": t.task_ref,
                        "pipeline_id": t.pipeline_id,
                    })
                if tt not in ACADEMIC_TYPES:
                    violations["INV-2"].append({
                        "id": t.id, "student": t.student.code,
                        "task_type": tt,
                    })

            if cat == "MANAGEMENT":
                if tt not in MANAGEMENT_TYPES:
                    violations["INV-3"].append({
                        "id": t.id, "student": t.student.code,
                        "task_type": tt, "task_ref": t.task_ref,
                    })
                if t.pipeline_id:
                    ref_pfx = _ref_prefix(t.task_ref)
                    book_pfx = ""
                    if t.pipeline and t.pipeline.paper_code:
                        book_pfx = t.pipeline.paper_code.split("-")[0].upper()
                    # only compare when both sides are known and ref is
                    # a subject-scoped ref (skip HANDWRITING/READING refs)
                    if ref_pfx and book_pfx and ref_pfx != book_pfx:
                        violations["INV-4"].append({
                            "id": t.id, "student": t.student.code,
                            "task_type": tt, "task_ref": t.task_ref,
                            "ref_prefix": ref_pfx,
                            "book_prefix": book_pfx,
                            "pipeline": t.pipeline.paper_code,
                        })

        any_v = any(violations[k] for k in violations)
        quiet = options["quiet"]

        # cron mode: silent when clean; loud when not.
        if quiet and not any_v and not options["json_out"]:
            return

        self.stdout.write("checked: " + str(total) + " StudentTask rows")
        self.stdout.write("")
        for key in ("INV-1", "INV-2", "INV-3", "INV-4"):
            rows = violations[key]
            self.stdout.write("%s  violations: %d" % (key, len(rows)))

        if not any_v:
            self.stdout.write("")
            self.stdout.write(self.style.SUCCESS("ALL INVARIANTS HELD"))
        else:
            self.stdout.write("")
            for key in ("INV-1", "INV-2", "INV-3", "INV-4"):
                rows = violations[key]
                if not rows:
                    continue
                self.stdout.write(self.style.WARNING(key + " samples (up to 10):"))
                for r in rows[:10]:
                    self.stdout.write("  " + json.dumps(r, ensure_ascii=False))

        if options["json_out"]:
            p = Path(options["json_out"])
            p.write_text(json.dumps({
                "total_scanned": total,
                "violations": violations,
                "counts": {k: len(v) for k, v in violations.items()},
            }, indent=2, ensure_ascii=False), encoding="utf-8")
            self.stdout.write("")
            self.stdout.write("json written: " + str(p))
