from django.core.management.base import BaseCommand
from django.utils import timezone


class Command(BaseCommand):
    help = 'Deletes expired retake exemptions.'

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

    def handle(self, *args, **options):
        from exams.models import RetakeExemption

        now = timezone.now()
        expired_qs = RetakeExemption.objects.filter(
            expires_at__isnull=False,
            expires_at__lt=now,
        )

        total = expired_qs.count()
        self.stdout.write(f'Found {total} expired exemption(s).')

        if options['dry_run']:
            for ex in expired_qs[:20]:
                self.stdout.write(f'  [DRY] {ex.student.code} D{ex.day_number}/{ex.subject}')
            self.stdout.write(self.style.WARNING('Dry run — no changes.'))
            return

        deleted, _ = expired_qs.delete()
        self.stdout.write(self.style.SUCCESS(f'Deleted {deleted} row(s).'))
