"""Build monthly result cards (Section 5.6).

Aggregates one calendar month of daily data per student into a
ParentReport row with period_kind=MONTH. Includes a simple tier
progress signal and an attendance ratio.

Standards: Guskey 2024 (communication device, not a data dump);
ESSA Report Card Design (at-a-glance first); NSW DoE plain language;
DBI/MTSS monthly progress monitoring; AERA/APA/NCME 2014 Std 13.7
(a stored value must name the construct it holds).
"""
from calendar import monthrange
from datetime import date as _date
from decimal import Decimal

from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

from exams.models import (Student, Exam, Attendance, DailyTask,
                     ParentReport, StudentTask, SkillAssessment)
from exams.pdf import save_result_card_pdf


BAND_ORDER = ["Excellent", "Good", "Fair", "Average", "Below Average", "Wrong"]


def _month_range(month_str):
    """Accept YYYY-MM and return (first_day, last_day)."""
    try:
        y_s, m_s = month_str.split("-")
        y = int(y_s)
        m = int(m_s)
        if not (1 <= m <= 12):
            raise ValueError
    except (ValueError, AttributeError):
        raise CommandError("Invalid --month, use YYYY-MM (e.g. 2026-10)")
    last_day = monthrange(y, m)[1]
    return _date(y, m, 1), _date(y, m, last_day)


def _tier_signal(pct):
    """Very simple tier-progress signal for the report card.

    Standards: MTSS tier movement; DBI progress monitoring.
    """
    if pct >= 70:
        return "tier-up-candidate"
    if pct >= 50:
        return "holding"
    return "tier-support"


class Command(BaseCommand):
    help = "Build monthly result cards from daily data."

    def add_arguments(self, parser):
        parser.add_argument("--month", required=True,
                            help="Calendar month, e.g. 2026-10")
        parser.add_argument("--code", default="",
                            help="Single student code; omit for all active students.")
        parser.add_argument("--pdf", action="store_true",
                            help="Render a monthly report card PDF per student.")

    def handle(self, *args, **options):
        first, last = _month_range(options["month"])
        if options["code"]:
            try:
                students = [Student.objects.get(code=options["code"], is_active=True)]
            except Student.DoesNotExist:
                raise CommandError("No active student with code " + options["code"])
        else:
            students = list(Student.objects.filter(is_active=True).order_by("code"))

        created = 0
        updated = 0
        make_pdf = bool(options.get("pdf"))
        pdf_paths = []
        with transaction.atomic():
            for s in students:
                report, was_new = self._build_one(s, first, last)
                tag = "new" if was_new else "updated"
                if was_new:
                    created += 1
                else:
                    updated += 1
                self.stdout.write(f"  {s.code} month {options['month']} - {tag} "
                                  f"({report.overall_progress})")
                if make_pdf:
                    try:
                        path = save_result_card_pdf(report)
                        pdf_paths.append(str(path))
                    except Exception as exc:
                        self.stderr.write("PDF fail " + s.code + ": " + str(exc))

        self.stdout.write(self.style.SUCCESS(
            f"Created: {created}, Updated: {updated}"))
        if make_pdf:
            self.stdout.write("PDFs: " + str(len(pdf_paths)))
            for pth in pdf_paths:
                self.stdout.write("  " + pth)

    def _build_one(self, student, first, last):
        exams = (Exam.objects.filter(student=student,
                                     exam_date__gte=first,
                                     exam_date__lte=last)
                 .order_by("exam_date", "question_index"))
        total_score = Decimal("0")
        total_max = Decimal("0")
        bands_count = {}
        subjects = set()
        for e in exams:
            sub = e.submissions.order_by("-created_at").first()
            if not sub or sub.ai_score is None:
                continue
            total_score += sub.ai_score
            total_max += e.max_marks
            subjects.add(e.subject)
            raw = sub.ai_raw if isinstance(sub.ai_raw, dict) else {}
            band = raw.get("band") or ""
            if band:
                bands_count[band] = bands_count.get(band, 0) + 1

        pct = round(float(total_score / total_max * 100), 1) if total_max else 0.0
        signal = _tier_signal(pct)
        overall = f"{pct}% ({total_score}/{total_max}) - {signal}" if total_max else "no graded work"

        att_total = Attendance.objects.filter(student=student,
                                              date__gte=first,
                                              date__lte=last).count()
        att_present = Attendance.objects.filter(student=student,
                                                date__gte=first,
                                                date__lte=last,
                                                present=True).count()
        att_ratio = (Decimal(att_present) / Decimal(att_total)
                     if att_total else None)

        strengths = [b for b in BAND_ORDER[:2] if bands_count.get(b)]
        weaknesses = [b for b in BAND_ORDER[-2:] if bands_count.get(b)]
        tasks = list(DailyTask.objects.filter(student=student,
                                              date_due__gte=first,
                                              date_due__lte=last)
                     .order_by("-date_due")[:8])

        strengths_text = ("Subjects seen: " + ", ".join(sorted(subjects)) + ". "
                          + ("Top bands: " + ", ".join(strengths) + "." if strengths else ""))[:2000]
        weaknesses_text = (", ".join(weaknesses)) if weaknesses else ""
        actions_text = " | ".join(t.description[:120] for t in tasks)

        # HW/RD (ACADEMIC) monthly summary.
        # Kirkpatrick 1959 (Level 1-2 learning outcomes reach the report);
        # MTSS/NCII (multi-measure progress monitoring);
        # AERA/APA/NCME 2014 Std 1.0 (each value names its construct);
        # DASH-2 (handwriting); Hasbrouck-Tindal 2017 (ORF).
        HW_RD_TYPES = {"HANDWRITING_EN": "Likhai (EN)",
                       "HANDWRITING_UR": "Likhai (UR)",
                       "READING_EN":     "Padhai (EN)",
                       "READING_UR":     "Padhai (UR)"}
        hw_rd_tasks = (StudentTask.objects
                       .filter(student=student,
                               task_type__in=list(HW_RD_TYPES.keys()),
                               unassigned_at__isnull=True)
                       .exclude(status="SKIPPED"))
        hw_rd_summary = {"done": 0, "pending": 0, "assessed": 0, "by_skill": {}}
        for tt, label in HW_RD_TYPES.items():
            done = hw_rd_tasks.filter(task_type=tt, status="DONE").count()
            open_ = hw_rd_tasks.filter(task_type=tt).exclude(status="DONE").count()
            n_assessed = (SkillAssessment.objects
                          .filter(student=student, skill_type=tt,
                                  assessed_at__gte=first,
                                  assessed_at__lte=last.isoformat() + "T23:59:59Z")
                          .count())
            if done + open_ + n_assessed:
                hw_rd_summary["by_skill"][label] = {
                    "done": done, "open": open_, "assessed": n_assessed}
            hw_rd_summary["done"] += done
            hw_rd_summary["pending"] += open_
            hw_rd_summary["assessed"] += n_assessed

        # week_number stays NULL for MONTH rows (AERA/APA/NCME 13.7).
        # Kaifiyat_e_Mizan snapshot at report time (Rule I; AERA Std 1.0;
        # Rule 10 one writer: recompute() is the sole writer of HealthScore,
        # this command only reads the current value and stores it on the report).
        from exams.mizan_algorithm import compute as _kzm_compute
        _kzm = _kzm_compute(student)
        kzm_score_val = _kzm["score"]
        kzm_band_val = _kzm["band"]

        defaults = {
            "week_number": None,
            "date_to": last,
            "overall_progress": overall[:50],
            "strengths": strengths_text,
            "weaknesses": weaknesses_text,
            "action_items": actions_text,
            "hw_rd_summary": hw_rd_summary,
            "kzm_score": kzm_score_val,
            "kzm_band": kzm_band_val,
            "attendance_ratio": att_ratio,
        }
        report, was_new = ParentReport.objects.update_or_create(
            student=student, period_kind="MONTH", date_from=first,
            defaults=defaults,
        )
        return report, was_new
