"""CI guard: never again allow trophy drift.

Fails the build if any active student violates:
    Sum(active PAPER_COMPLETE.count) == pace × passing_paper_days
"""
from collections import defaultdict
from django.test import TestCase
from django.db.models import Sum
from exams.models import Student, AttemptLog
from exams.models_trophy import TrophyEvent
from exams.services.trophy_service import _best_attempt, PASS_THRESHOLD


class PaperUnitInvariantTest(TestCase):

    def test_every_student_matches_paper_formula(self):
        failures = []
        for s in Student.objects.filter(is_active=True):
            pace = s.daily_question_count or 1
            by_pd = defaultdict(list)
            for a in (AttemptLog.objects.filter(student=s)
                      .exclude(score__isnull=True).exclude(max_score=0)
                      .select_related("question__paper")):
                if a.target_day_number is None:
                    continue
                by_pd[(a.target_day_number, a.question.paper_id)].append(a)
            passing = 0
            for attempts in by_pd.values():
                best, ratio = _best_attempt(attempts)
                if best and ratio >= PASS_THRESHOLD:
                    passing += 1
            expected = passing * pace
            actual = (TrophyEvent.objects
                      .filter(student=s, cancelled_at__isnull=True,
                              event_key__startswith="PAPER_COMPLETE:")
                      .aggregate(t=Sum("count"))["t"] or 0)
            if actual != expected:
                failures.append(
                    f"{s.code}: expected={expected} actual={actual} "
                    f"delta={actual-expected:+d} "
                    f"(passing_paper_days={passing}, pace={pace})"
                )
        self.assertEqual(
            failures, [],
            "Trophy ledger invariant violated:\n" + "\n".join(failures)
        )

    def test_no_legacy_prefixes_in_active_ledger(self):
        bad = (TrophyEvent.objects
               .filter(cancelled_at__isnull=True)
               .exclude(event_key__startswith="PAPER_COMPLETE:"))
        self.assertEqual(
            bad.count(), 0,
            f"{bad.count()} non-PAPER_COMPLETE rows still active in the ledger"
        )
