"""proportional_audit - per-stage CVI check.

Standards: Polit & Beck 2007 (I-CVI >= 0.78, S-CVI/Ave >= 0.90);
ISO 8000-8 5.2-5.5; ALCOA+ Complete; PAL states; Rule 9; Rule 26.
"""
import json
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path
from django.core.management.base import BaseCommand
from exams.models import (StudentTask, TaskPipeline, Student,
                          KnowledgeComponent, ModelQuestion, CorrectionLog)

STAGES = [1, 3, 5, 6, 7, 10, 11]
LABEL = {1: "BOOK_INGEST", 3: "KC_DISCOVERY", 5: "KC_TAG",
         6: "KC_MISCONCEPTION", 7: "KC_SOCRATIC_LADDER",
         10: "GLOSSARY", 11: "STORY"}
INTACT = 0.90
MARGINAL = 0.78


def _stem_prefixes(ref):
    # Map book/paper ref like "CS-9" to KC code prefixes as used in DB.
    # Real KC codes observed: C9-CS, C9-CH, C9-UR, C9-MT, C9-IS, C9-ISL,
    # C9-EN, C9-PH, C9-BI, C9-TQ, plus a legacy UR9- form. Verified 2026-10-12.
    stem = (ref or "").split("-")[0].upper()
    return ["C9-" + stem, stem + "9-", "C9-" + stem + "L"]


def present(t):
    tt = t.task_type
    ref = t.task_ref or ""
    if tt == "BOOK_INGEST":
        p = ref.split("-BOOK")[0]
        return ModelQuestion.objects.filter(
            paper__code__startswith=p,
            superseded_at__isnull=True).exists()
    if tt == "KC_DISCOVERY":
        for pre in _stem_prefixes(ref):
            if KnowledgeComponent.objects.filter(code__startswith=pre).exists():
                return True
        return False
    if tt == "KC_TAG":
        for pre in _stem_prefixes(ref):
            if ModelQuestion.objects.filter(kc_code__startswith=pre).exists():
                return True
        return False
    if tt == "KC_MISCONCEPTION":
        kc = KnowledgeComponent.objects.filter(code=ref).first()
        return bool(kc and (kc.misconceptions or []))
    if tt == "KC_SOCRATIC_LADDER":
        kc = KnowledgeComponent.objects.filter(code=ref).first()
        return bool(kc and (kc.socratic_ladder or []))
    if tt == "GLOSSARY":
        kc = KnowledgeComponent.objects.filter(code=ref).first()
        return bool(kc and (kc.key_terms or []))
    if tt == "STORY":
        kc = KnowledgeComponent.objects.filter(code=ref).first()
        return bool(kc and kc.story)
    return False


class Command(BaseCommand):
    help = "Proportional pipeline audit. --apply to reassign."

    def add_arguments(self, p):
        p.add_argument("--apply", action="store_true")
        p.add_argument("--student", default=None)
        p.add_argument("--out", default="/home/orkoworo/idealogy/tmp/proportional_audit.json")

    def handle(self, *a, **o):
        apply = o["apply"]
        qs = Student.objects.filter(is_active=True).order_by("code")
        if o["student"]:
            qs = qs.filter(code=o["student"])

        rep = {"when": datetime.now(timezone.utc).isoformat(),
               "students": [], "fixes": [],
               "totals": {"INTACT": 0, "MARGINAL": 0, "BROKEN": 0,
                          "INCOMPLETE": 0, "reassign": 0}}

        for s in qs:
            s_rep = {"code": s.code, "name": s.name, "pipelines": []}
            for p in TaskPipeline.objects.filter(owner_student=s):
                tasks = list(StudentTask.objects.filter(pipeline=p))
                bs = defaultdict(list)
                for t in tasks:
                    bs[t.pipeline_stage or 0].append(t)
                stages_out = []
                for st in STAGES:
                    rs = bs.get(st, [])
                    done = [t for t in rs if t.status == "DONE"]
                    if not done:
                        stages_out.append({
                            "stage": st, "label": LABEL[st],
                            "total": len(rs), "done": 0, "s_cvi": None,
                            "state": "INCOMPLETE", "reassign": []})
                        rep["totals"]["INCOMPLETE"] += 1
                        continue
                    icvi = {t.id: (1 if present(t) else 0) for t in done}
                    cvi = sum(icvi.values()) / len(icvi)
                    if cvi >= INTACT:
                        state = "INTACT"; to_ra = []
                    elif cvi >= MARGINAL:
                        state = "MARGINAL"
                        to_ra = [tid for tid, v in icvi.items() if v == 0]
                    else:
                        state = "BROKEN"; to_ra = [t.id for t in done]
                    rep["totals"][state] += 1
                    rep["totals"]["reassign"] += len(to_ra)
                    stages_out.append({
                        "stage": st, "label": LABEL[st],
                        "total": len(rs), "done": len(done),
                        "s_cvi": round(cvi, 4), "state": state,
                        "reassign": to_ra})
                    if apply and to_ra:
                        for tid in to_ra:
                            t = StudentTask.objects.filter(pk=tid).first()
                            if not t: continue
                            old = t.status
                            t.status = "ASSIGNED"
                            t.ingest_status = "PENDING"
                            t.ingest_error = ((t.ingest_error or "")[:300]
                                + " | reassigned: missing data (I-CVI=0)")
                            t.save(update_fields=["status","ingest_status","ingest_error"])
                            CorrectionLog.objects.create(
                                kind="MODEL", target_model="StudentTask",
                                target_id=t.id, field_name="status",
                                old_value=old, new_value="ASSIGNED",
                                reason=f"proportional audit {LABEL[st]} I-CVI=0",
                                actor_label="terminal:teacher")
                            rep["fixes"].append({"task": t.id,
                                                 "student": s.code, "stage": st})
                s_rep["pipelines"].append({
                    "paper_code": p.paper_code,
                    "current_stage": p.current_stage,
                    "stages": stages_out})
            rep["students"].append(s_rep)

        out = Path(o["out"])
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(json.dumps(rep, indent=2) + "\n", encoding="utf-8")
        self.stdout.write(f"wrote {out}")
        for k, v in rep["totals"].items():
            self.stdout.write(f"  {k}: {v}")
