"""Health Centre writer (Phase 2.4a).

Canonical writer for HealthEvent + HealthScore recompute.
Every violation/credit passes through apply_policy(). No direct writes
elsewhere (Rule 10 — one canonical writer per table).

Standards: Amazon AHR; EWS ABC; PBIS (4:1); Goss v. Lopez 1975;
ISO 27001 A.8.15; Rule 9 (append-only); Rule 10; Rule 12 (Mizan);
Rule 13 (HITL via overridden_by); Rule 14 (category split).
"""
from django.db import transaction
from django.utils import timezone

from exams.models import (
    HealthPolicy, HealthEvent, HealthScore, PortalFeatureLog, Student,
)


BASELINE = 500


def _band_for(score):
    if score >= 700:
        return "HEALTHY"
    if score >= 400:
        return "WATCH"
    if score >= 200:
        return "AT_RISK"
    return "CRITICAL"


@transaction.atomic
def apply_policy(student, policy_code, reason,
                 source="AUTO", actor=None, evidence=None):
    """Apply a HealthPolicy to a student.

    - Looks up HealthPolicy by code (fails loud if missing).
    - Writes one HealthEvent (append-only).
    - Recomputes HealthScore (idempotent, deterministic).
    - Logs band change to PortalFeatureLog only on transition.

    Returns (event, old_band, new_band, old_score, new_score).
    """
    if not isinstance(student, Student):
        raise TypeError("student must be a Student instance")

    try:
        policy = HealthPolicy.objects.get(code=policy_code, is_active=True)
    except HealthPolicy.DoesNotExist:
        raise ValueError("Unknown or inactive policy: " + str(policy_code))

    event = HealthEvent.objects.create(
        student=student,
        policy=policy,
        kind=policy.kind,
        points=policy.points,
        reason=(reason or "")[:2000],
        evidence=(evidence or {}),
        source=source,
        actor=actor,
    )

    # Recompute (same logic as health_recalc, inlined to avoid subprocess)
    from django.db.models import Sum
    agg = (HealthEvent.objects
           .filter(student=student)
           .aggregate(total=Sum("points")))
    total = agg["total"] or 0
    raw = BASELINE + total
    score = max(0, min(1000, raw))
    new_band = _band_for(score)

    hs, _ = HealthScore.objects.get_or_create(student=student)
    old_band = hs.band
    old_score = hs.score

    hs.score = score
    hs.band = new_band
    hs.event_count = HealthEvent.objects.filter(student=student).count()
    hs.last_event_at = event.created_at

    if new_band in ("AT_RISK", "CRITICAL"):
        if hs.red_flag_since is None:
            hs.red_flag_since = timezone.now()
    else:
        hs.red_flag_since = None

    if new_band == "HEALTHY":
        if hs.green_shield_since is None:
            hs.green_shield_since = timezone.now()
    else:
        hs.green_shield_since = None

    hs.save()

    if old_band != new_band:
        PortalFeatureLog.objects.create(
            key="health_band." + student.code,
            old_enabled=(old_band == "HEALTHY"),
            new_enabled=(new_band == "HEALTHY"),
            changed_by=actor,
            note=("band " + old_band + "(" + str(old_score) + ")"
                  + " -> " + new_band + "(" + str(score) + ")"),
        )

    return event, old_band, new_band, old_score, score


def override_event(event, teacher, reason):
    """Teacher override of a HealthEvent.

    Marks overridden_by/at/reason on the event, then recomputes.
    The event itself is NOT deleted (Rule 9). If the teacher wants to
    neutralise the points, they override the event to zero (write a
    compensating event) — this function only stamps the override.

    Standards: EU AI Act Art. 14; Rule 13 (HITL); ISO 27001 A.8.15.
    """
    event.overridden_by = teacher
    event.overridden_at = timezone.now()
    event.override_reason = (reason or "")[:2000]
    event.save(update_fields=["overridden_by", "overridden_at",
                              "override_reason"])
    return event
