"""rebalance_kc_ladder_tasks - redistribute KC_SOCRATIC_LADDER tasks
across all MT-enrolled active students, keeping Rule 25 exclusivity.

Rule: one KC -> one student at a time (Rule 25). Distribute evenly so no
single student carries the whole workload (MTSS/NCII; Womack & Jones).

Steps:
  1. Read open KC_SOCRATIC_LADDER tasks (ASSIGNED, IN_PROGRESS).
  2. Unique KC list = the work to distribute.
  3. Eligible students = active students whose enrolled_subjects include
     the KC's subject prefix.
  4. Mark old rows SKIPPED (Rule 9).
  5. Create new rows round-robin across eligible students.

Standards: Rule 9, Rule 10, Rule 14, Rule 25, Rule 24, MTSS/NCII,
Womack & Jones, ISO/IEC/IEEE 29119-3, ISO 27001 A.8.15.
"""
from collections import defaultdict
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.utils import timezone
from exams.models import StudentTask, KnowledgeComponent, Student

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


class Command(BaseCommand):
    help = "Rebalance KC_SOCRATIC_LADDER tasks across all eligible students."
    def add_arguments(self, p):
        p.add_argument("--apply", action="store_true")
        p.add_argument("--max-per-student", type=int, default=12)
        p.add_argument("--subject", type=str, required=True,
                       help="DEF-048: rebalance only this subject prefix (MT, CH, PH, ...). "
                            "Cross-subject rebalance is forbidden by Rule 14 / MTSS/NCII.")
    def handle(self, *a, **o):
        # DEF-048 (2026-10-09): require --subject. Root cause of non-Math ladder
        # tasks landing on Math-focused students (Hassan) was that this command
        # rebalanced across all subjects at once, using enrolled_subjects as the
        # eligibility filter. Standards: ISO 9001:2015 10.2 (cause, not symptom);
        # Rule 14 (teacher-directed MANAGEMENT); MTSS/NCII (subject focus); Rule 26.
        sub = (o.get("subject") or "").strip().upper()
        if not sub:
            raise CommandError("--subject is required (MT, CH, PH, ...).")
        pfx_codes = "C9-" + sub + "-"
        qs = StudentTask.objects.filter(
            task_type="KC_SOCRATIC_LADDER",
            status__in=["ASSIGNED", "IN_PROGRESS"],
            task_ref__startswith=pfx_codes)

        kc_codes = sorted(set(qs.values_list("task_ref", flat=True)))
        self.stdout.write("open KC_SOCRATIC_LADDER rows: " + str(qs.count()))
        self.stdout.write("unique KCs to distribute: " + str(len(kc_codes)))

        kcs = {kc.code: kc for kc in KnowledgeComponent.objects.filter(code__in=kc_codes)}

        # Eligible students by prefix
        students = list(Student.objects.filter(is_active=True).order_by("code"))
        eligible = {}
        for prefix in {PFX.get(k.subject or "", "") for k in kcs.values()}:
            if not prefix:
                continue
            # Only the requested subject participates (Rule 14; MTSS/NCII).
            if prefix != sub:
                continue
            eligible[prefix] = [s for s in students
                                if prefix in (s.enrolled_subjects or [])]

        self.stdout.write("--- eligible counts per prefix ---")
        for p, lst in sorted(eligible.items()):
            self.stdout.write("  " + p + ": " + str(len(lst)))

        # Round-robin assignment, respecting --max-per-student
        plan = []
        load = defaultdict(int)
        rr_idx = defaultdict(int)
        for code in kc_codes:
            kc = kcs.get(code)
            if not kc:
                continue
            prefix = PFX.get(kc.subject or "", "")
            pool = eligible.get(prefix) or []
            if not pool:
                self.stdout.write("  SKIP (no eligible student): " + code)
                continue
            # find next student under cap
            n = len(pool)
            chosen = None
            for _ in range(n * 2):
                cand = pool[rr_idx[prefix] % n]
                rr_idx[prefix] += 1
                if load[cand.code] < o["max_per_student"]:
                    chosen = cand
                    break
            if chosen is None:
                self.stdout.write("  SKIP (all at cap): " + code)
                continue
            plan.append((chosen.code, code, prefix))
            load[chosen.code] += 1

        self.stdout.write("--- planned distribution ---")
        for code, n in sorted(load.items()):
            self.stdout.write("  " + code + ": " + str(n))
        self.stdout.write("  total new rows: " + str(len(plan)))

        if not o["apply"]:
            self.stdout.write("(DRY RUN - pass --apply to write)")
            return

        now = timezone.now()
        with transaction.atomic():
            for t in qs:
                t.status = "SKIPPED"
                t.unassigned_at = now
                t.notes = ((t.notes or "")
                           + "\n[rebalance 2026-10-08] replaced for even distribution").strip()
                t.save(update_fields=["status", "unassigned_at", "notes"])
            created = 0
            for code, ref, _pfx in plan:
                StudentTask.objects.create(
                    student=Student.objects.get(code=code),
                    task_type="KC_SOCRATIC_LADDER",
                    task_ref=ref,
                    status="ASSIGNED",
                    category="MANAGEMENT",
                    assigned_by=None,
                )
                created += 1
        self.stdout.write("Applied: marked " + str(qs.count())
                          + " SKIPPED; created " + str(created) + " new rows.")
