"""One-off: scan every student's StudentDayMission rows and stamp completion
for any day already at SAFAR. Safe to run repeatedly (idempotent)."""
from django.core.management.base import BaseCommand
from exams.models import Student
from exams.services.day_completion import complete_all_reachable_days


class Command(BaseCommand):
    help = "Backfill StudentDayCompletion from existing StudentDayMission state."

    def add_arguments(self, parser):
        parser.add_argument('--student-id', type=int, default=None)

    def handle(self, *args, **opts):
        qs = Student.objects.filter(is_active=True)
        if opts['student_id']:
            qs = qs.filter(id=opts['student_id'])
        total = 0
        for s in qs.iterator():
            done = complete_all_reachable_days(s)
            if done:
                self.stdout.write(f"student {s.id} ({s.code}): completed days {done}")
                total += len(done)
        self.stdout.write(self.style.SUCCESS(f"Backfill OK: {total} completions created."))
