"""Backfill missing SDM positions (position=None) based on question_index order.

Runs once. Idempotent. Safe to re-run.
"""
from django.core.management.base import BaseCommand
from django.db.models import Count
from exams.models_day_mission import StudentDayMission


class Command(BaseCommand):
    help = "Backfill SDM positions where position is NULL, ordered by question_index."

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

    def handle(self, *args, **opts):
        total = StudentDayMission.objects.filter(position__isnull=True).count()
        self.stdout.write(f"Rows with NULL position: {total}")

        if total == 0:
            self.stdout.write(self.style.SUCCESS("Nothing to backfill."))
            return

        if opts.get('dry_run'):
            self.stdout.write("[DRY RUN] Would update these rows.")
            return

        # Group by (student, day, subject) and assign positions in question_index order
        groups = StudentDayMission.objects.filter(position__isnull=True).values(
            'student_id', 'day_number', 'subject'
        ).annotate(n=Count('id'))

        self.stdout.write(f"Processing {len(groups)} groups...")
        updated = 0

        for grp in groups:
            rows = list(StudentDayMission.objects.filter(
                student_id=grp['student_id'],
                day_number=grp['day_number'],
                subject=grp['subject'],
                position__isnull=True,
            ).order_by('question__question_index', 'id'))

            # Find max existing position in this group to continue from
            max_pos = StudentDayMission.objects.filter(
                student_id=grp['student_id'],
                day_number=grp['day_number'],
                subject=grp['subject'],
                position__isnull=False,
            ).aggregate(m=__import__('django.db.models', fromlist=['Max']).Max('position'))['m'] or 0

            for i, sdm in enumerate(rows, start=max_pos + 1):
                sdm.position = i
                sdm.save(update_fields=['position'])
                updated += 1

        self.stdout.write(self.style.SUCCESS(f"Backfilled {updated} SDM rows."))
