from django.test import TestCase, Client
from exams.models import Student, EngineState
from exams.models_day_mission import StudentDayMission


class MissionVisibilityTest(TestCase):
    """
    Industry standard invariant: SDM is the source of truth for what
    a student should see. Computed stages (current_stage, aggregate_stage)
    must NEVER silently hide SDM-assigned questions from the default view.
    """

    def test_all_sdm_questions_visible_by_default(self):
        """Every SDM question for today MUST appear on the mission page by default."""
        student = Student.objects.filter(code='S-0017').first()
        if not student:
            self.skipTest("S-0017 not found in test DB")

        eng = EngineState.objects.first()
        if not eng:
            self.skipTest("No engine state")

        cur_day = eng.get_current_day()
        sdm = StudentDayMission.objects.filter(
            student=student, day_number=cur_day
        )
        if sdm.count() == 0:
            self.skipTest("No SDM for today")

        client = Client()
        client.force_login(student.student_user)
        response = client.get('/api/portal/daily-mission-v3/', secure=True)

        self.assertEqual(response.status_code, 200)
        html = response.content.decode()

        # At least 5 Q badges should render (one per subject slot)
        import re
        badges = len(re.findall(r'Q#?\d+', html))
        self.assertGreater(
            badges, 0,
            f"SDM has {sdm.count()} questions but 0 Q badges rendered. "
            f"Stage filter likely hid them."
        )

    def test_explicit_stage_filter_still_works(self):
        """When user clicks a specific stage, filter should apply."""
        student = Student.objects.filter(code='S-0017').first()
        if not student:
            self.skipTest("S-0017 not found")

        client = Client()
        client.force_login(student.student_user)
        response = client.get(
            '/api/portal/daily-mission-v3/?stage=STUDY',
            secure=True
        )
        self.assertEqual(response.status_code, 200)
        # Response should still render (not crash) — filter is valid behavior
