"""Red flags + passing-chance per REPORT-CARD-RED-FLAG-SPEC-v1.0.
Standards: AERA/APA/NCME 2014 Std 1.0 + 13.7; Angoff 1971; EWS ABC;
MTSS/NCII; DASH-2; Hasbrouck & Tindal 2017; FERPA; Rule G; Rule H;
IN-12; IN-22.
"""
from datetime import timedelta
from django.utils import timezone

RF_LABELS = {
    "RF-01": "Hazri kam",
    "RF-02": "Likhawat kamzor",
    "RF-03": "Parhai mein rukawat",
    "RF-04": "Subject neeche ja raha",
    "RF-05": "Book adhoori",
    "RF-06": "Behaviour incident",
}


def compute_red_flags(student, as_of=None):
    """Return list of measured red flags. Impression is never a flag."""
    as_of = as_of or timezone.now().date()
    out = []

    # RF-01 attendance < 80% over last 30 days
    try:
        from .models import Attendance
        since = as_of - timedelta(days=30)
        att = Attendance.objects.filter(student=student, date__gte=since, date__lte=as_of)
        total = att.count()
        present = att.filter(present=True).count()
        if total >= 10:
            pct = round(present / total * 100, 1)
            if pct < 80:
                out.append({"id": "RF-01", "label_ur": RF_LABELS["RF-01"],
                            "value": str(pct) + "%", "threshold": "< 80%",
                            "standard": "EWS ABC; BISE eligibility",
                            "action_ur": "Agle 7 din mein hazri theek karein."})
    except Exception:
        pass

    # RF-04 subject trending down
    try:
        from .models import Exam
        since90 = as_of - timedelta(days=90)
        exams = (Exam.objects.filter(student=student, exam_date__gte=since90)
                 .order_by("subject", "exam_date"))
        by_subj = {}
        for e in exams:
            sub = e.submissions.order_by("-created_at").first()
            if sub is None or sub.ai_score is None or not e.max_marks:
                continue
            by_subj.setdefault(e.subject, []).append(float(sub.ai_score) / float(e.max_marks))
        for subj, fracs in by_subj.items():
            if len(fracs) >= 3:
                tail = fracs[-3:]
                if tail[0] > tail[1] > tail[2] and (tail[0] - tail[2]) >= 0.15:
                    out.append({"id": "RF-04",
                                "label_ur": RF_LABELS["RF-04"] + " - " + subj,
                                "value": " - ".join("%.0f%%" % (f * 100) for f in tail),
                                "threshold": "3 down probes, drop >= 15pp",
                                "standard": "MTSS / NCII trend-line",
                                "action_ur": subj + " par 14 din ka focused plan."})
    except Exception:
        pass

    # RF-05 book completion < 60% per book code
    try:
        from .models import StudentTask
        books = {}
        for t in StudentTask.objects.filter(student=student, task_type="BOOK_INGEST"):
            ref = (t.task_ref or "").split("#", 1)[0]
            if not ref:
                continue
            books.setdefault(ref, {"done": 0, "total": 0})
            books[ref]["total"] += 1
            if t.status == "DONE":
                books[ref]["done"] += 1
        for ref, d in books.items():
            if d["total"] >= 5:
                pct = round(d["done"] / d["total"] * 100, 1)
                if pct < 60:
                    out.append({"id": "RF-05",
                                "label_ur": RF_LABELS["RF-05"] + " - " + ref,
                                "value": str(d["done"]) + " of " + str(d["total"])
                                         + " (" + str(pct) + "%)",
                                "threshold": "< 60%",
                                "standard": "Rule 14 (ACADEMIC measure)",
                                "action_ur": "Baqi " + str(d["total"] - d["done"])
                                             + " pages 14 din mein."})
    except Exception:
        pass

    # RF-02 handwriting critical (DASH-2 EN < 21; Urdu rubric < 26)
    try:
        from .models import SkillAssessment
        for st, thr in (("HANDWRITING_EN", 21), ("HANDWRITING_UR", 26)):
            row = (SkillAssessment.objects
                   .filter(student=student, skill_type=st)
                   .order_by("-assessed_at").first())
            if row is None:
                continue
            sd = row.score_data or {}
            total = sd.get("total")
            flagged = False
            if total is not None:
                try:
                    if float(total) < thr:
                        flagged = True
                except Exception:
                    pass
            if row.band in ("CRITICAL", "BELOW_AVG"):
                flagged = True
            if flagged:
                out.append({
                    "id": "RF-02",
                    "label_ur": RF_LABELS["RF-02"] + " - " + st,
                    "value": ("total=" + str(total)) if total is not None else ("band=" + row.band),
                    "threshold": "EN < 21 OR UR < 26 (DASH-2 / IEEE Access 2024)",
                    "standard": "DASH-2 (Pearson); IEEE Access 2024",
                    "action_ur": "Roz 10-12 minute likhawat mashq.",
                })
    except Exception:
        pass

    # RF-03 reading critical (WCPM < 10th pctile OR comp <= 1/8)
    try:
        from .models import SkillAssessment
        for st in ("READING_EN", "READING_UR"):
            row = (SkillAssessment.objects
                   .filter(student=student, skill_type=st)
                   .order_by("-assessed_at").first())
            if row is None:
                continue
            sd = row.score_data or {}
            wpm = sd.get("wpm") or sd.get("wcpm")
            comp = sd.get("comp_total") or sd.get("comprehension")
            flagged = False
            if wpm is not None:
                try:
                    if float(wpm) < 60:
                        flagged = True
                except Exception:
                    pass
            if comp is not None:
                try:
                    if float(comp) <= 1:
                        flagged = True
                except Exception:
                    pass
            if row.band in ("CRITICAL", "BELOW_AVG"):
                flagged = True
            if flagged:
                out.append({
                    "id": "RF-03",
                    "label_ur": RF_LABELS["RF-03"] + " - " + st,
                    "value": ("wpm=" + str(wpm) if wpm is not None else "")
                             + (", comp=" + str(comp) if comp is not None else "")
                             + (", band=" + row.band if not (wpm or comp) else ""),
                    "threshold": "WCPM < 60 OR comp <= 1/8",
                    "standard": "Hasbrouck & Tindal 2017; NAEP 2026",
                    "action_ur": "Roz 15 min buland awaz parhai.",
                })
    except Exception:
        pass

    # RF-06 behaviour High/Critical (>=2 HIGH OR >=1 CRITICAL in last 30d)
    try:
        from .models import BehaviourIncident
        since30 = as_of - timedelta(days=30)
        qs = BehaviourIncident.objects.filter(student=student, created_at__date__gte=since30)
        n_high = qs.filter(severity="HIGH").count()
        n_crit = qs.filter(severity="CRITICAL").count()
        if n_high >= 2 or n_crit >= 1:
            out.append({
                "id": "RF-06",
                "label_ur": RF_LABELS["RF-06"],
                "value": "HIGH=" + str(n_high) + ", CRITICAL=" + str(n_crit),
                "threshold": ">=2 HIGH OR >=1 CRITICAL (30d)",
                "standard": "PBIS; Goss v. Lopez 1975",
                "action_ur": "Teacher se baat karein aur sahi rawaiya apnayein.",
            })
    except Exception:
        pass

    return out


def passing_chance(student, as_of=None):
    """Return {'ready': bool, 'missing': [labels]}. No number without all P1-P6."""
    as_of = as_of or timezone.now().date()
    missing = []

    try:
        from .models import Attendance
        since30 = as_of - timedelta(days=30)
        n = Attendance.objects.filter(student=student, date__gte=since30).count()
        if n < 10:
            missing.append("P1 attendance history 30+ days")
    except Exception:
        missing.append("P1 attendance history 30+ days")

    try:
        from .models import SkillAssessment
        n_hw = SkillAssessment.objects.filter(student=student).filter(
            skill_type__icontains="HAND").count()
        if n_hw < 3:
            missing.append("P2 handwriting 3+ assessments")
    except Exception:
        missing.append("P2 handwriting 3+ assessments")

    try:
        from .models import SkillAssessment
        n_rd = SkillAssessment.objects.filter(student=student).filter(
            skill_type__icontains="READ").count()
        if n_rd < 3:
            missing.append("P3 reading ORF 3+ probes")
            missing.append("P4 reading comprehension 3+ probes")
    except Exception:
        missing.append("P3 reading ORF 3+ probes")
        missing.append("P4 reading comprehension 3+ probes")

    try:
        from .models import Exam
        subj = set(Exam.objects.filter(student=student)
                   .values_list("subject", flat=True))
        if len(subj) < 4:
            missing.append("P5 graded work in 4+ subjects")
    except Exception:
        missing.append("P5 graded work in 4+ subjects")

    missing.append("P6 documented validity basis / teacher waiver")

    if missing:
        return {"ready": False, "missing": missing}
    return {"ready": True, "missing": [], "pct": None, "ci": None, "model": "v1"}
