from django.core.management.base import BaseCommand
from exams.models import Student, AttemptLog
from exams.models_trophy import TrophyEvent
from exams.services.trophy_service import recompute_choice_trophy, recompute_question_trophy, _best_attempt
PASS_THRESHOLD = 0.60

class Command(BaseCommand):
    help = "Idempotent trophy backfill (default: CHOICE mode; default: dry-run)"
    def add_arguments(self, p):
        p.add_argument("--apply", action="store_true")
        p.add_argument("--student", type=str, default=None)
        p.add_argument("--respect-mode", action="store_true")

    def handle(self, *args, **opts):
        apply = opts["apply"]; only = opts["student"]; respect = opts["respect_mode"]
        if not apply: self.stdout.write(self.style.WARNING("DRY RUN — pass --apply to commit"))
        students = Student.objects.filter(is_active=True).order_by("code")
        if only: students = students.filter(code=only)
        stats = dict(created=0, replaced=0, cancelled=0, noop=0, skip=0)
        for s in students:
            pace = s.daily_question_count or 1
            groups = {}
            for a in (AttemptLog.objects.filter(student=s).exclude(score__isnull=True).exclude(max_score=0).select_related("question__paper")):
                day = a.target_day_number
                subj = getattr(getattr(a.question, "paper", None), "subject", "") or ""
                if day is None or not subj:
                    stats["skip"] += 1; continue
                groups.setdefault((day, subj), []).append(a)

            for (day, subj), rows in groups.items():
                is_choice = True
                if respect:
                    is_choice = any(isinstance(a.result_json, dict) and (a.result_json.get("copied_from") or a.result_json.get("mode") == "CHOICE_TEST") for a in rows)
                if not apply:
                    if is_choice:
                        _, ratio = _best_attempt(rows)
                        ek = f"CHOICE_COMPLETE:{s.id}:{day}:{subj}"
                        exists = TrophyEvent.objects.filter(event_key=ek, cancelled_at__isnull=True).exists()
                        if ratio < PASS_THRESHOLD: stats["cancelled" if exists else "noop"] += 1
                        else: stats["created" if not exists else "noop"] += 1
                    continue
                is_physical = any(getattr(a, 'is_physical', False) for a in rows)
                if is_choice or is_physical:
                    act, _ = recompute_choice_trophy(s, day, subj, rows, pace=pace)
                else:
                    by_q = {}
                    for a in rows: by_q.setdefault(a.question_id, []).append(a)
                    act = "individual"
                    for qrows in by_q.values():
                        recompute_question_trophy(s, day, qrows[0].question, qrows, pace=pace)
                stats[act if act in stats else "noop"] += 1

        self.stdout.write(self.style.SUCCESS(f"created={stats['created']} replaced={stats['replaced']} cancelled={stats['cancelled']} noop={stats['noop']} skipped_null={stats['skip']}"))
