"""Build weekly parent reports (Section 5.6).

Aggregates one ISO week of daily data per student into a ParentReport
row. Optionally renders a PDF into output/weekly_reports/.

Standards: Guskey (communication device, not data dump);
NSW DoE plain-language; ESSA Report Card Design; DBI/MTSS weekly
progress monitoring; Hattie & Timperley (where-to-next).
"""
from datetime import date as _date, timedelta as _td
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


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


def _iso_week_range(week_str):
    """Accept YYYY-Www and return (monday, sunday) as date objects."""
    try:
        y_s, w_s = week_str.split("-W")
        y = int(y_s)
        w = int(w_s)
        monday = _date.fromisocalendar(y, w, 1)
    except (ValueError, AttributeError):
        raise CommandError("Invalid --week, use YYYY-Www (e.g. 2026-W40)")
    sunday = monday + _td(days=6)
    return monday, sunday


class Command(BaseCommand):
    help = "Build weekly ParentReport rows from daily data."

    def add_arguments(self, parser):
        parser.add_argument("--week", required=True,
                            help="ISO week, e.g. 2026-W40")
        parser.add_argument("--code", default="",
                            help="Single student code; omit for all active students.")

    def handle(self, *args, **options):
        monday, sunday = _iso_week_range(options["week"])
        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
        with transaction.atomic():
            for s in students:
                report, was_new = self._build_one(s, monday, sunday)
                if report is None:
                    continue
                tag = "new" if was_new else "updated"
                if was_new:
                    created += 1
                else:
                    updated += 1
                self.stdout.write(f"  {s.code} week {options['week']} - {tag} "
                                  f"({report.overall_progress})")

        self.stdout.write(self.style.SUCCESS(
            f"Created: {created}, Updated: {updated}"))

    def _build_one(self, student, monday, sunday):
        exams = (Exam.objects.filter(student=student,
                                     exam_date__gte=monday,
                                     exam_date__lte=sunday)
                 .order_by("exam_date", "question_index"))
        total_score = Decimal("0")
        total_max = Decimal("0")
        bands_count = {}
        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
            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
        overall = f"{pct}% ({total_score}/{total_max})" if total_max else "no graded work"

        att_total = Attendance.objects.filter(student=student,
                                              date__gte=monday,
                                              date__lte=sunday).count()
        att_present = Attendance.objects.filter(student=student,
                                                date__gte=monday,
                                                date__lte=sunday,
                                                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=monday,
                                              date_due__lte=sunday)
                     .order_by("-date_due")[:5])

        strengths_text = ", ".join(strengths) if strengths else ""
        weaknesses_text = ", ".join(weaknesses) if weaknesses else ""
        actions_text = " | ".join(t.description[:120] for t in tasks)

        week_num = monday.isocalendar()[1]
        defaults = {
            "date_from": monday,
            "date_to": sunday,
            "overall_progress": overall[:50],
            "strengths": strengths_text,
            "weaknesses": weaknesses_text,
            "action_items": actions_text,
            "attendance_ratio": att_ratio,
        }
        report, was_new = ParentReport.objects.update_or_create(
            student=student, week_number=week_num, date_from=monday,
            defaults=defaults,
        )
        return report, was_new
