"""Recompute HealthScore for one or all students from HealthEvent stream.

Model (Amazon AHR, design/HEALTH-CENTRE-POLICY-v1.0.1.md s1):
  score = clamp(500 + sum(events.points), 0, 1000)
  bands: HEALTHY>=700, WATCH>=400, AT_RISK>=200, CRITICAL<200

Idempotent. Never edits HealthEvent rows. Writes band-change logs to
PortalFeatureLog only on transition.

Standards: Amazon AHR; ISO 9001:2015 8.5.1 (deterministic recompute);
ISO 27001 A.8.15 (band-change logging); Rule 9 (append-only events);
Rule 12 (Mizan computes).
"""
from django.core.management.base import BaseCommand
from django.db import transaction
from django.db.models import Sum
from django.utils import timezone

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

BASELINE = 500


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


def _recompute_for(student):
    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()
    last_event = (HealthEvent.objects
                  .filter(student=student)
                  .order_by("-created_at")
                  .values_list("created_at", flat=True)
                  .first())
    hs.last_event_at = last_event

    # red_flag_since: first time entering AT_RISK or CRITICAL
    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

    # green_shield_since: first time entering HEALTHY (only track start)
    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()

    # Band-change log (only on transition, one write per change)
    if old_band != new_band:
        PortalFeatureLog.objects.create(
            key="health_band." + student.code,
            old_enabled=True,
            new_enabled=(new_band == "HEALTHY"),
            note=("band " + old_band + "(" + str(old_score) + ")"
                  + " -> " + new_band + "(" + str(score) + ")"),
        )
    return old_score, score, old_band, new_band


class Command(BaseCommand):
    help = "Recompute HealthScore for one or all students."

    def add_arguments(self, parser):
        parser.add_argument("--code", type=str, default="",
                            help="Recompute only this student (S-XXXX).")
        parser.add_argument("--all", action="store_true",
                            help="Recompute all active students.")
        parser.add_argument("--dry-run", action="store_true")

    @transaction.atomic
    def handle(self, *args, **options):
        code = (options["code"] or "").strip().upper()
        dry = options["dry_run"]

        if code:
            students = list(Student.objects.filter(code=code))
        elif options["all"]:
            students = list(Student.objects.filter(is_active=True))
        else:
            self.stderr.write("Specify --code S-XXXX or --all")
            return

        if not students:
            self.stderr.write("No students matched.")
            return

        for s in students:
            if dry:
                agg = (HealthEvent.objects.filter(student=s)
                       .aggregate(total=Sum("points")))
                total = agg["total"] or 0
                raw = BASELINE + total
                score = max(0, min(1000, raw))
                band = _band_for(score)
                self.stdout.write(
                    s.code + " -> " + str(score) + " (" + band + ") "
                    + "[dry]")
                continue
            old_score, score, old_band, new_band = _recompute_for(s)
            marker = ""
            if old_band != new_band:
                marker = " *band change*"
            self.stdout.write(
                s.code + " " + str(old_score) + "(" + old_band + ")"
                + " -> " + str(score) + "(" + new_band + ")" + marker)
