"""investigate_stage - per (book, stage) pipeline investigation.

Standards: ISO 8000-8 5.2-5.5 (data quality dimensions);
Polit & Beck 2007 (I-CVI >= 0.78, S-CVI/Ave >= 0.90);
NCES/EDFacts 0.85 (proportionality floor);
ALCOA+ Complete; PAL Pipeline Audit Layer; Rule 9; Rule 26; Rule 28.

Usage:
  python manage.py investigate_stage --book CH-9 --stage 1
  python manage.py investigate_stage --book CH-9 --stage 1 --out tmp/x.json
"""
import json
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path

from django.core.management.base import BaseCommand
from django.db.models import Q

from exams.models import StudentTask, KnowledgeComponent, ModelQuestion


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     # Polit & Beck S-CVI/Ave pass
MARGINAL = 0.78   # Polit & Beck item-level pass
PROP_FLOOR = 0.85 # NCES/EDFacts proportionality floor

PASS = "PASS"
PARTIAL = "PARTIAL"
FAIL = "FAIL"
NOT_REACHED = "NOT_REACHED"


def _stem_prefixes(ref):
    # 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 _scope(book, stage):
    """Real task_ref shape differs per stage (C-11 lesson)."""
    stem = (book or "").split("-")[0].upper()
    if stage == 1:
        return {"task_ref__startswith": stem + "-9-BOOK"}
    if stage in (3, 5):
        return {"task_ref": stem + "-9"}
    q = Q(task_ref__startswith="C9-" + stem) | \
        Q(task_ref__startswith=stem + "9-")
    return {"_q_": q}


def produced_data_exists(task):
    tt = task.task_type
    ref = task.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":
        return any(KnowledgeComponent.objects.filter(
            code__startswith=pre).exists() for pre in _stem_prefixes(ref))
    if tt == "KC_TAG":
        return any(ModelQuestion.objects.filter(
            kc_code__startswith=pre).exists() for pre in _stem_prefixes(ref))
    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 getattr(kc, "story_text", None))
    return False


class Command(BaseCommand):
    help = "Per (book, stage) pipeline investigation. Read-only."

    def add_arguments(self, parser):
        parser.add_argument("--book", required=True,
                            help="Book code e.g. CH-9, PH-9, MT-9, IS-9")
        parser.add_argument("--stage", required=True, type=int,
                            choices=STAGES)
        parser.add_argument("--out", default=None,
                            help="Override output JSON path")

    def handle(self, *args, **opts):
        book = opts["book"].upper()
        stage = opts["stage"]
        tt = LABEL[stage]
        scope = _scope(book, stage)

        if "_q_" in scope:
            qs = StudentTask.objects.filter(scope["_q_"], task_type=tt)
        else:
            qs = StudentTask.objects.filter(task_type=tt, **scope)
        qs = qs.order_by("id")

        by_status = Counter(qs.values_list("status", flat=True))
        done = list(qs.filter(status="DONE"))
        present = [t for t in done if produced_data_exists(t)]
        missing = [t for t in done if t not in present]
        n_done = len(done)
        n_prod = len(present)

        if not qs.exists():
            verdict = NOT_REACHED
        elif not done:
            verdict = FAIL
        else:
            r = n_prod / n_done
            verdict = PASS if r >= INTACT else (PARTIAL if r >= MARGINAL else FAIL)

        ev = {
            "book": book,
            "stage": stage,
            "task_type": tt,
            "investigated_at": datetime.now(timezone.utc).isoformat(),
            "tasks": {
                "total": qs.count(),
                "by_status": dict(by_status),
                "done": n_done,
                "done_with_produced_data": n_prod,
                "done_missing_data": len(missing),
            },
            "s_cvi_ave": round(n_prod / n_done, 4) if n_done else 0.0,
            "thresholds": {
                "s_cvi_ave_pass": INTACT,
                "i_cvi_item_pass": MARGINAL,
                "proportionality_floor": PROP_FLOOR,
            },
            "verdict": verdict,
            "missing_data": [
                {"task_id": t.id, "student": t.student.code,
                 "task_ref": t.task_ref} for t in missing[:50]
            ],
        }

        out = Path(opts["out"]) if opts["out"] else \
            Path("tmp/investigation") / f"{book}_stage{stage}.json"
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(json.dumps(ev, indent=2))

        self.stdout.write(f"=== {book} stage {stage} ({tt}) ===")
        self.stdout.write(f"  total={qs.count()}  by_status={dict(by_status)}")
        self.stdout.write(f"  DONE={n_done}  with_data={n_prod}  missing={len(missing)}")
        self.stdout.write(f"  S-CVI/Ave={ev['s_cvi_ave']}  VERDICT={verdict}")
        self.stdout.write(f"  evidence={out}")
