"""Close stale StudentQuestionLock rows (is_active=False)."""
from django.core.management.base import BaseCommand
from exams.models import Student, EngineState, StudentQuestionLock
from exams.models_day_mission import StudentDayMission

class Command(BaseCommand):
    help = "Close stale question locks not in current day's mission"

    def add_arguments(self, parser):
        parser.add_argument('--dry-run', action='store_true')

    def handle(self, *args, **opts):
        eng = EngineState.objects.first()
        day = eng.get_current_day() if (eng and eng.has_started) else 1
        self.stdout.write(f"Current day: {day}")

        total_closed = 0
        for student in Student.objects.filter(is_active=True):
            today_qids = set(StudentDayMission.objects.filter(
                student=student, day_number=day
            ).values_list('question_id', flat=True))

            stale = StudentQuestionLock.objects.filter(
                student=student, is_active=True
            ).exclude(question_id__in=today_qids)

            n = stale.count()
            if n == 0:
                continue

            if opts.get('dry_run'):
                self.stdout.write(f"  [DRY] {student.code}: would close {n} locks")
            else:
                closed = stale.update(is_active=False)
                total_closed += closed

        self.stdout.write(self.style.SUCCESS(
            f"{'[DRY] ' if opts.get('dry_run') else ''}Total closed: {total_closed}"
        ))
