"""Skill assessment engine (Phase 4.1b, 2026-10-08).

Canonical writer for SkillAssessment (handwriting EN/UR, reading EN/UR).
Design: design/HANDWRITING-SPEC-v1.0.md; design/READING-SPEC-v1.0.md
Standards: DASH-2 (Pearson 2024); IEEE Access 2024 (Nastaliq 6 aspects);
Hasbrouck & Tindal 2017 (WCPM percentile bands);
NAEP 2026 comprehension targets; AERA/APA/NCME 2014 Std 1.0;
ISO 27001 A.8.15; Rule 9 (append-only); Rule 10 (one writer);
Rule 12 (Mizan); Rule 13 (HITL).
"""
from django.db import transaction
from django.utils import timezone

from exams.models import (
    SkillAssessment, Student, HealthEvent, PortalFeatureLog,
)
from exams.health import apply_policy


# Band thresholds per spec.

# Handwriting English: DASH-2 total 5-25 (lower = better)
# Excellent 5-8, Good 9-12, Fair 13-16, Below Avg 17-20, Critical 21-25
def _band_hw_en(total):
    if total <= 8:   return "EXCELLENT"
    if total <= 12:  return "GOOD"
    if total <= 16:  return "FAIR"
    if total <= 20:  return "BELOW_AVG"
    return "CRITICAL"


# Handwriting Urdu: Nastaliq total 6-30 (lower = better)
# Excellent 6-10, Good 11-15, Fair 16-20, Below Avg 21-25, Critical 26-30
def _band_hw_ur(total):
    if total <= 10:  return "EXCELLENT"
    if total <= 15:  return "GOOD"
    if total <= 20:  return "FAIR"
    if total <= 25:  return "BELOW_AVG"
    return "CRITICAL"


# Reading: band from WCPM percentile AND comprehension total (0-8)
# Spec: Excellent >=175; Good 145-174; Fair 115-144; Below Avg 90-114; Critical < 90
def _band_reading(wpm, comp_total=None):
    if wpm >= 175:   band = "EXCELLENT"
    elif wpm >= 145: band = "GOOD"
    elif wpm >= 115: band = "FAIR"
    elif wpm >= 90:  band = "BELOW_AVG"
    else:            band = "CRITICAL"
    # Comprehension can pull band down (NAEP targets)
    if comp_total is not None:
        if comp_total >= 7 and band in ("EXCELLENT", "GOOD"):
            band = "EXCELLENT"
        elif comp_total <= 1 and band in ("FAIR", "BELOW_AVG"):
            band = "CRITICAL"
    return band


BANDERS = {
    "HANDWRITING_EN": lambda d: _band_hw_en(int(d.get("total", 25))),
    "HANDWRITING_UR": lambda d: _band_hw_ur(int(d.get("total", 30))),
    "READING_EN":     lambda d: _band_reading(
                          int(d.get("wpm", 0)),
                          d.get("comprehension_total")),
    "READING_UR":     lambda d: _band_reading(int(d.get("wpm", 0)), None),
}


# Policy code per (skill, direction).
# Improvement policies fire on positive delta; worsening on negative.
IMPROVE_POLICY = {
    "HANDWRITING_EN": {2: "CR-HW-IMPROVE-2", 5: "CR-HW-IMPROVE-5"},
    "HANDWRITING_UR": {2: "CR-HW-IMPROVE-2", 5: "CR-HW-IMPROVE-5"},
    "READING_EN":     {10: "CR-RD-IMPROVE-10", 20: "CR-RD-IMPROVE-20"},
    "READING_UR":     {10: "CR-RD-IMPROVE-10", 20: "CR-RD-IMPROVE-20"},
}


def _prior_total(student, skill_type):
    """Return last total (or wpm) for this skill, or None."""
    prior = (SkillAssessment.objects
             .filter(student=student, skill_type=skill_type)
             .order_by("-assessed_at")
             .first())
    if not prior:
        return None
    d = prior.score_data or {}
    if skill_type.startswith("HANDWRITING"):
        return d.get("total")
    if skill_type.startswith("READING"):
        return d.get("wpm")
    return None


@transaction.atomic
def record_assessment(student, skill_type, score_data, actor=None,
                      notes_ur="", assessed_at=None):
    """Record one assessment. Append-only.

    Fires at most one CR-* policy if the improvement crosses the
    next threshold; fires POL-TSK-002-like violation if a HW practice
    day was skipped (that is a separate call, not this one).

    Returns (assessment, improvement_points).
    """
    if not isinstance(student, Student):
        raise TypeError("student must be a Student instance")
    if skill_type not in BANDERS:
        raise ValueError("Unknown skill_type: " + str(skill_type))

    band = BANDERS[skill_type](score_data)

    prior = _prior_total(student, skill_type)
    improvement = None
    if prior is not None:
        current = score_data.get("total") if skill_type.startswith("HANDWRITING") else score_data.get("wpm")
        if current is not None:
            # For handwriting, lower is better; improvement = prior - current.
            # For reading, higher is better; improvement = current - prior.
            if skill_type.startswith("HANDWRITING"):
                improvement = prior - current
            else:
                improvement = current - prior

    assessment = SkillAssessment.objects.create(
        student=student,
        skill_type=skill_type,
        assessed_at=(assessed_at or timezone.now()),
        assessed_by=actor,
        score_data=score_data,
        band=band,
        notes_ur=(notes_ur or "")[:2000],
    )

    PortalFeatureLog.objects.create(
        key="skill_assess." + student.code + "." + skill_type,
        old_enabled=False, new_enabled=True,
        changed_by=actor,
        note=("band=" + band + " improvement=" + str(improvement)
              + " data=" + str(score_data)[:150]),
    )

    # Fire improvement credit if crossed a threshold (once).
    if improvement is not None and improvement > 0:
        for threshold in sorted(IMPROVE_POLICY[skill_type].keys(), reverse=True):
            if improvement >= threshold:
                pol = IMPROVE_POLICY[skill_type][threshold]
                # Idempotence: only fire if this student has not fired
                # this policy from THIS skill before.
                already = HealthEvent.objects.filter(
                    student=student, policy__code=pol,
                    evidence__skill=skill_type).exists()
                if not already:
                    try:
                        apply_policy(
                            student, pol,
                            reason=("Improvement +" + str(improvement)
                                    + " in " + skill_type),
                            source="AUTO", actor=actor,
                            evidence={"skill": skill_type,
                                      "assessment_id": assessment.id,
                                      "improvement": improvement},
                        )
                    except Exception:
                        pass
                break

    return assessment, improvement
