"""assign_kc_tasks - KC_MISCONCEPTION assignment (subject-scoped).

Subject-scope guard (2026-10-08, DEF-003 recurrence): a KC is assigned only
to a student whose enrolled subjects include the KC's subject prefix.
Enrolled subjects = BOOK_INGEST task refs + Exam.subject (same rule as
exams/views.py). Fails safe: empty set = student skipped.

Standards: NIST SP 800-53 SI-10; Saltzer & Schroeder 1975;
AERA/APA/NCME 2014 Std 1.0; Rule 10 (guard at the writer);
Womack & Jones Lean Thinking (muda); Section 15.4;
ISO 21500:2021 4.3.3; Rule H.
"""
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from exams.models import Student, StudentTask, KnowledgeComponent
from exams.ownership import check_unique_owner

_PFX = {"Mathematics": "MT", "Physics": "PH", "Chemistry": "CH",
        "Biology": "BI", "English": "EN", "Urdu": "UR",
        "Islamiyat": "IS", "Computer Science": "CS",
        "Tarjumatul Quran": "TQ"}


def _enrolled(student):
    """Thin shim - delegates to the canonical reader (Rule 10)."""
    from exams.enrollment import enrolled_prefixes
    return enrolled_prefixes(student)


class Command(BaseCommand):
    help = "Create KC_MISCONCEPTION StudentTask rows (subject-scoped, one KC per student)"

    def add_arguments(self, parser):
        parser.add_argument("--students", type=str, required=True)
        parser.add_argument("--only-empty", action="store_true")
        parser.add_argument("--codes", type=str, default=None)
        parser.add_argument("--subject", type=str, default=None,
                            help="DEF-047: required with --only-empty; e.g. MT, CH, PH")
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **options):
        codes_in = [s.strip().upper()
                    for s in options["students"].split(",") if s.strip()]
        students = list(Student.objects.filter(code__in=codes_in).order_by("code"))
        if not students:
            raise CommandError("no valid students in --students")
        missing = set(codes_in) - {s.code for s in students}
        if missing:
            raise CommandError("students not found: " + ", ".join(sorted(missing)))

        if options["codes"]:
            codes = [c.strip().upper()
                     for c in options["codes"].split(",") if c.strip()]
        elif options["only_empty"]:
            # DEF-047 (2026-10-09): require --subject. Root cause of CH-KC leakage to
            # Math-focused students (Ifta, Hassan) was that --only-empty swept
            # every empty KC across every subject, then distributed by load-balance.
            # Standards: ISO 9001:2015 10.2 (address cause, not symptom);
            # Rule 10 (teacher directs KC assignment); Rule 14; MTSS/NCII; Rule 26.
            sub = (options.get("subject") or "").strip().upper()
            if not sub:
                raise CommandError(
                    "--only-empty requires --subject XX (e.g. MT, CH, PH). "
                    "Auto-selection across all subjects is forbidden by Rule 14 / DEF-047.")
            pfx = "C9-" + sub + "-"
            qs = (KnowledgeComponent.objects
                  .filter(code__startswith=pfx)
                  .exclude(code="C9-CH00-GLOSSARY").order_by("code"))
            codes = [kc.code for kc in qs if not (kc.misconceptions or [])]
        else:
            raise CommandError("pass --only-empty or --codes")

        active = set(StudentTask.objects
                     .filter(task_type="KC_MISCONCEPTION",
                             status__in=["ASSIGNED", "IN_PROGRESS"])
                     .values_list("task_ref", flat=True))
        codes = [c for c in codes if c not in active]

        enrolled = {s.code: _enrolled(s) for s in students}
        no_scope = [s.code for s in students if not enrolled[s.code]]
        if no_scope:
            self.stdout.write("WARNING: no enrolled subjects for "
                              + ", ".join(no_scope) + " - skipped (fail-safe).")

        kc_by_code = {kc.code: kc
                      for kc in KnowledgeComponent.objects.filter(code__in=codes)}
        prefix = {}
        for c in codes:
            kc = kc_by_code.get(c)
            p = _PFX.get((kc.subject if kc else "") or "", "")
            if p:
                prefix[c] = p
        codes = [c for c in codes if c in prefix]

        if not codes:
            self.stdout.write("No KCs to assign (all have misconceptions, "
                              "an active task, or no mapped subject).")
            return

        self.stdout.write("Students (" + str(len(students)) + "): "
                          + ", ".join(s.code for s in students))
        self.stdout.write("Candidate KCs after filters: " + str(len(codes)))

        assigned = {s.code: [] for s in students}
        for c in codes:
            p = prefix[c]
            elig = [s for s in students if p in enrolled[s.code]]
            if not elig:
                self.stdout.write("SKIP (no eligible student): " + c)
                continue
            elig.sort(key=lambda s: (len(assigned[s.code]), s.code))
            assigned[elig[0].code].append(c)

        created = 0
        with transaction.atomic():
            for s in students:
                for code in assigned[s.code]:
                    ok, other = check_unique_owner(code, s, "MANAGEMENT")
                    if not ok:
                        self.stdout.write(
                            "REFUSED (Rule 25): " + code
                            + " already owned by " + str(other))
                        continue
                    if options["dry_run"]:
                        self.stdout.write("[dry] " + s.code + "  " + code)
                    else:
                        StudentTask.objects.create(
                            student=s, task_type="KC_MISCONCEPTION",
                            task_ref=code, status="ASSIGNED",
                            assigned_by=None,
                        )
                    created += 1

        self.stdout.write("--- per student ---")
        for s in students:
            self.stdout.write("  " + s.code + ": " + str(len(assigned[s.code])))
        self.stdout.write("--- total: " + str(created) + " tasks")
        if options["dry_run"]:
            self.stdout.write("(DRY RUN - nothing written)")
