"""Ensure all 9th class students have SDM rows for Days 1 to current_day.

Idempotent — safe to run multiple times.
Guarantees "same pace same miss = same result" across students.
"""
from django.core.management.base import BaseCommand
from exams.models import Student, EngineState
from exams.services.daily_mission_engine import get_daily_mission_questions


class Command(BaseCommand):
    help = "Backfill SDM for all 9th class students so missing penalty is consistent."

    def handle(self, *args, **options):
        engine = EngineState.objects.filter(id=1).first()
        if not engine or not engine.has_started:
            self.stdout.write(self.style.WARNING("Engine not started - skipping."))
            return

        current_day = engine.get_current_day()
        self.stdout.write(f"Current day: {current_day}")

        students = Student.objects.filter(is_active=True)
        processed = 0
        failed = 0
        skipped = 0
        for student in students:
            cls = (student.student_class or '').strip().lower()
            if not cls.startswith('9'):
                skipped += 1
                continue

            pace = student.daily_question_count or 1
            try:
                get_daily_mission_questions(
                    student,
                    pace_per_book=pace,
                    curriculum_day=current_day,
                )
                processed += 1
            except Exception as e:
                failed += 1
                self.stderr.write(f"  {student.code}: {e}")

        self.stdout.write(self.style.SUCCESS(
            f"Processed: {processed}, Failed: {failed}, Skipped (non-9th): {skipped}"
        ))
