"""Print accumulated progress for one student.

Standards: DBI (time-series progress), MTSS (attendance + tier),
Hattie & Timperley (where-am-I-going feedback).
"""
from decimal import Decimal
from statistics import mean

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

from exams.models import Student, Exam, Attendance, DailyTask


def _pct(n, d):
    if not d:
        return 0.0
    return round(float(n) / float(d) * 100, 1)


def _segments(rows, gap_days=14):
    """Split date-sorted rows into contiguous segments.

    A gap longer than gap_days breaks the time-series. Trend and
    recent-list are computed within the LAST segment only.

    Standards: DBI/MTSS progress monitoring (NCII); the absence of
    data is not a decline.
    """
    if not rows:
        return []
    segs = [[rows[0]]]
    for r in rows[1:]:
        if (r[0] - segs[-1][-1][0]).days > gap_days:
            segs.append([r])
        else:
            segs[-1].append(r)
    return segs


class Command(BaseCommand):
    help = "Accumulated progress report for one student (text)."

    def add_arguments(self, parser):
        parser.add_argument("code", type=str)

    def handle(self, *args, **options):
        code = options["code"].strip()
        try:
            s = Student.objects.get(code=code, is_active=True)
        except Student.DoesNotExist:
            raise CommandError("Student not found: " + code)

        exams = Exam.objects.filter(student=s).order_by("exam_date", "question_index")
        subs_by_exam = {}
        for e in exams:
            sub = e.submissions.order_by("-created_at").first()
            if sub:
                subs_by_exam[e.id] = sub

        att_total = Attendance.objects.filter(student=s).count()
        att_present = Attendance.objects.filter(student=s, present=True).count()
        tasks_total = DailyTask.objects.filter(student=s).count()
        tasks_done = DailyTask.objects.filter(student=s, completed=True).count()

        self.stdout.write("")
        self.stdout.write("=" * 60)
        self.stdout.write("PROGRESS: " + s.name + " (" + s.code + ")")
        self.stdout.write("Tier " + str(s.tier) + " | " + s.get_student_class_display() + " | " + s.shift)
        self.stdout.write("=" * 60)
        self.stdout.write("Attendance: " + str(att_present) + "/" + str(att_total) + " = " + str(_pct(att_present, att_total)) + "%")
        self.stdout.write("Tasks: " + str(tasks_done) + "/" + str(tasks_total) + " completed")
        self.stdout.write("")

        by_subject = {}
        for e in exams:
            sub = subs_by_exam.get(e.id)
            if not sub or sub.ai_score is None:
                continue
            by_subject.setdefault(e.subject, []).append((e.exam_date, sub.ai_score, e.max_marks))

        if not by_subject:
            self.stdout.write("No graded exams yet.")
            return

        total_score = Decimal("0")
        total_max = Decimal("0")
        for subj in sorted(by_subject):
            rows = by_subject[subj]
            sc = sum((r[1] for r in rows), Decimal("0"))
            mx = sum((r[2] for r in rows), Decimal("0"))
            total_score += sc
            total_max += mx
            pct = _pct(sc, mx)
            self.stdout.write("-" * 60)
            self.stdout.write(subj + "  (" + str(len(rows)) + " questions)")
            self.stdout.write("  Average: " + str(pct) + "%")
            segs = _segments(rows)
            last_seg = segs[-1] if segs else []
            if len(last_seg) >= 2:
                mid = len(last_seg) // 2
                first = [r[1] for r in last_seg[:mid]]
                last = [r[1] for r in last_seg[mid:]]
                first_mx = sum((r[2] for r in last_seg[:mid]), Decimal("0"))
                last_mx = sum((r[2] for r in last_seg[mid:]), Decimal("0"))
                f_pct = _pct(sum(first, Decimal("0")), first_mx)
                l_pct = _pct(sum(last, Decimal("0")), last_mx)
                delta = round(l_pct - f_pct, 1)
                arrow = "IMPROVING" if delta > 3 else "DECLINING" if delta < -3 else "STEADY"
                span = (last_seg[-1][0] - last_seg[0][0]).days
                day_word = "day" if span == 1 else "days"
                self.stdout.write("  Trend: " + arrow + " (" + str(delta)
                                  + "% change over last " + str(span)
                                  + " " + day_word + ", " + str(len(last_seg)) + " obs)")
            else:
                self.stdout.write("  Trend: INSUFFICIENT recent data "
                                  "(fewer than 2 observations in last contiguous segment).")
            if len(segs) > 1:
                self.stdout.write("  Note: " + str(len(segs) - 1)
                                  + " gap(s) > 14 days ignored for trend.")
            recent = last_seg[-3:]
            self.stdout.write("  Recent:")
            for d, sc2, mx2 in recent:
                self.stdout.write("    " + str(d) + "  " + str(sc2) + "/" + str(mx2))

        self.stdout.write("-" * 60)
        self.stdout.write("OVERALL: " + str(total_score) + "/" + str(total_max) + " = " + str(_pct(total_score, total_max)) + "%")
        self.stdout.write("=" * 60)
