"""Align StudentQuestionLock to StudentDayMission.

SAFE: only CREATES missing locks. Never deletes or deactivates.
Deactivation of stale locks is a separate, later, one-off command.

Usage:
    manage.py reconcile_locks_to_sdm --day 6
    manage.py reconcile_locks_to_sdm --all-days
    manage.py reconcile_locks_to_sdm --day 6 --dry-run
"""
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.db import transaction

from exams.models import StudentQuestionLock, EngineState, Student
from exams.models_day_mission import StudentDayMission


class Command(BaseCommand):
    help = "Create missing StudentQuestionLock rows for existing SDM rows."

    def add_arguments(self, parser):
        parser.add_argument('--day', type=int, default=None)
        parser.add_argument('--all-days', action='store_true')
        parser.add_argument('--dry-run', action='store_true')

    def handle(self, *args, **opts):
        dry = opts['dry_run']
        engine = EngineState.objects.filter(id=1).first()

        if opts['all_days']:
            days = sorted(set(
                StudentDayMission.objects
                .values_list('day_number', flat=True).distinct()
            ))
        elif opts['day']:
            days = [opts['day']]
        else:
            days = [
                engine.get_current_day()
                if (engine and engine.has_started) else 1
            ]

        self.stdout.write(f"Days: {days}  dry_run={dry}")
        total = 0
        per_student = {}

        for day in days:
            rows = (
                StudentDayMission.objects
                .filter(day_number=day)
                .values_list('student_id', 'question_id')
            )
            for sid, qid in rows:
                exists = StudentQuestionLock.objects.filter(
                    student_id=sid, question_id=qid, is_active=True
                ).exists()
                if exists:
                    continue
                per_student[sid] = per_student.get(sid, 0) + 1
                if not dry:
                    with transaction.atomic():
                        StudentQuestionLock.objects.update_or_create(
                            student_id=sid, question_id=qid,
                            defaults={'is_active': True,
                                      'locked_at': timezone.now()},
                        )
                total += 1

        style = self.style.SUCCESS if not dry else self.style.WARNING
        self.stdout.write(style(
            f"{'[DRY]' if dry else '[APPLIED]'} "
            f"created {total} missing locks across {len(per_student)} students"
        ))
        for sid, n in sorted(per_student.items(), key=lambda kv: -kv[1])[:25]:
            code = Student.objects.filter(id=sid).values_list('code', flat=True).first()
            self.stdout.write(f"  {code or sid}: +{n}")
