from datetime import timedelta
from django.test import TestCase
from django.utils import timezone
from exams.models import Student, AttemptLog
from exams.models_trophy import TrophyEvent
from exams.services.trophy_service import (
    recompute_choice_trophy, recompute_subject_trophies,
)

# --- INDUSTRY STANDARD DYNAMIC MODEL RESOLUTION ---
# We don't guess the model names. We ask the ORM what AttemptLog actually points to.
QuestionModel = AttemptLog._meta.get_field('question').related_model
PaperModel = QuestionModel._meta.get_field('paper').related_model

class TrophyLedgerTests(TestCase):
    def setUp(self):
        self.s = Student.objects.create(code="T-0001", name="Test")
        self.p = PaperModel.objects.create(subject="Chemistry")
        self.now = timezone.now()

    def _mk(self, day, rows):
        out = []
        for score, mx, days_ago in rows:
            q = QuestionModel.objects.create(paper=self.p, text="q")
            a = AttemptLog.objects.create(
                student=self.s, question=q, score=score, max_score=mx,
                target_day_number=day, is_physical=True)
            # Force created_at since auto_now_add ignores kwargs
            AttemptLog.objects.filter(pk=a.pk).update(
                created_at=self.now - timedelta(days=days_ago))
            a.refresh_from_db()
            out.append(a)
        return out

    def test_first_pass_creates_dated_at_attempt(self):
        rows = self._mk(5, [(1.5, 2, 3)])
        act, te = recompute_choice_trophy(self.s, 5, "Chemistry", rows)
        self.assertEqual(act, "created")
        self.assertEqual(te.date, (self.now - timedelta(days=3)).date())
        self.assertEqual(te.count, self.s.daily_question_count)

    def test_below_threshold_no_trophy(self):
        rows = self._mk(5, [(1.0, 2, 3)])
        self.assertEqual(recompute_choice_trophy(self.s, 5, "Chemistry", rows)[0], "noop")

    def test_wrong_date_replaced_append_only(self):
        rows = self._mk(5, [(1.5, 2, 3)])
        TrophyEvent.objects.create(
            student=self.s,
            event_key=f"CHOICE_COMPLETE:{self.s.id}:5:Chemistry",
            date=(self.now - timedelta(days=99)).date(),
            reason="QUESTION_COMPLETE", pace=1, base_count=1, count=1,
            subject="Chemistry")
        act, te = recompute_choice_trophy(self.s, 5, "Chemistry", rows)
        self.assertEqual(act, "replaced")
        self.assertEqual(te.date, (self.now - timedelta(days=3)).date())
        old = TrophyEvent.objects.get(
            event_key=te.event_key, cancelled_at__isnull=False)
        self.assertNotEqual(old.id, te.id)

    def test_idempotent(self):
        rows = self._mk(5, [(1.5, 2, 3)])
        self.assertEqual(recompute_choice_trophy(self.s, 5, "Chemistry", rows)[0], "created")
        self.assertEqual(recompute_choice_trophy(self.s, 5, "Chemistry", rows)[0], "noop")

    def test_fail_after_pass_cancels_not_deletes(self):
        passing = self._mk(5, [(1.5, 2, 3)])
        recompute_choice_trophy(self.s, 5, "Chemistry", passing)
        failing = self._mk(5, [(0.5, 2, 1)])
        act, _ = recompute_choice_trophy(self.s, 5, "Chemistry", failing)
        self.assertEqual(act, "cancelled")
        self.assertEqual(
            TrophyEvent.objects.filter(cancelled_at__isnull=True).count(), 0)
        self.assertEqual(
            TrophyEvent.objects.filter(cancelled_at__isnull=False).count(), 1)

    def test_physical_upload_defaults_to_choice(self):
        self._mk(5, [(1.5, 2, 3)])
        act, te = recompute_subject_trophies(self.s, 5, "Chemistry")
        self.assertEqual(act, "created")
        self.assertTrue(te.event_key.startswith("CHOICE_COMPLETE:"))
        self.assertEqual(te.subject, "Chemistry")
