from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils import timezone
from exams.models_trophy import TrophyEvent
VALID = {c[0] for c in TrophyEvent.REASON_CHOICES}

class Command(BaseCommand):
    help = "Repair TrophyEvent ledger (append-only-safe)."
    def add_arguments(self, p):
        p.add_argument("--apply", action="store_true")
        p.add_argument("--migrate-legacy-prefix", action="store_true")
        p.add_argument("--fix-invalid-reasons", action="store_true")
        p.add_argument("--fill-null-subject", action="store_true")

    def handle(self, *a, **opts):
        if not opts["apply"]:
            self.stdout.write(self.style.WARNING("DRY RUN — pass --apply"))
        with transaction.atomic():
            if opts["migrate_legacy_prefix"]: self._legacy(opts["apply"])
            if opts["fix_invalid_reasons"]:   self._reasons(opts["apply"])
            if opts["fill_null_subject"]:     self._subject(opts["apply"])

    def _legacy(self, apply):
        qs = TrophyEvent.objects.filter(event_key__startswith="BACKFILL_CHOICE:", cancelled_at__isnull=True)
        n = qs.count()
        self.stdout.write(f"[legacy-prefix] active={n}")
        if apply and n:
            self.stdout.write(self.style.SUCCESS(f"cancelled {qs.update(cancelled_at=timezone.now())}"))

    def _reasons(self, apply):
        qs = TrophyEvent.objects.filter(cancelled_at__isnull=True).exclude(reason__in=VALID)
        n = qs.count()
        self.stdout.write(f"[invalid-reasons] active={n}")
        if apply and n:
            self.stdout.write(self.style.SUCCESS(f"cancelled {qs.update(cancelled_at=timezone.now())}"))

    def _subject(self, apply):
        qs = TrophyEvent.objects.filter(cancelled_at__isnull=True, subject="", event_key__startswith="Q_COMPLETE:")
        n = qs.count()
        self.stdout.write(f"[null-subject] active={n}")
        if not apply or n == 0: return
        
        from exams.models import AttemptLog
        QuestionModel = AttemptLog._meta.get_field('question').related_model
        
        fixed = 0
        for t in qs.iterator():
            try: qid = int(t.event_key.split(":")[3])
            except (ValueError, IndexError): continue
            q = QuestionModel.objects.select_related("paper").filter(pk=qid).first()
            subj = getattr(getattr(q, "paper", None), "subject", "") or ""
            if subj:
                TrophyEvent.objects.filter(pk=t.pk).update(subject=subj)
                fixed += 1
        self.stdout.write(self.style.SUCCESS(f"filled subject on {fixed} rows"))
