"""One-time migration: cancel CHOICE/Q rows, backfill PAPER_COMPLETE rows.
Default is DRY-RUN. Pass --apply to write. Pass --student S-XXXX to test one.
"""
from collections import defaultdict
from django.core.management.base import BaseCommand
from django.db import transaction
from django.db.models import Sum
from django.utils import timezone
from exams.models import Student, AttemptLog
from exams.models_trophy import TrophyEvent
from exams.services.trophy_service import _best_attempt, PASS_THRESHOLD


class Command(BaseCommand):
    help = "Migrate trophy ledger to PAPER_COMPLETE unit (pace x passing paper-days)."

    def add_arguments(self, parser):
        parser.add_argument("--apply", action="store_true", help="Write changes (default: dry-run)")
        parser.add_argument("--student", type=str, default=None, help="Only one student code")

    def handle(self, *args, **opts):
        apply = opts["apply"]
        only = opts["student"]
        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)

        grand = {"created": 0, "cancelled": 0, "students": 0, "old": 0, "new": 0}

        for s in students:
            pace = s.daily_question_count or 1
            base = (AttemptLog.objects.filter(student=s)
                    .exclude(score__isnull=True).exclude(max_score=0)
                    .select_related("question__paper"))

            by_paper_day = defaultdict(list)
            for a in base:
                if a.target_day_number is None:
                    continue
                by_paper_day[(a.target_day_number, a.question.paper_id)].append(a)

            passing = []
            for (day, paper_id), attempts in by_paper_day.items():
                best, ratio = _best_attempt(attempts)
                if best and ratio >= PASS_THRESHOLD:
                    passing.append((day, paper_id, best.created_at.date(), attempts[0].question.paper))

            old_sum = TrophyEvent.objects.filter(student=s, cancelled_at__isnull=True).aggregate(t=Sum("count"))["t"] or 0
            new_sum = len(passing) * pace

            if old_sum == 0 and new_sum == 0:
                continue

            delta = new_sum - old_sum
            self.stdout.write(
                f"{s.code}: pace={pace}  paper_days={len(by_paper_day)}  "
                f"passing={len(passing)}  old={old_sum}  new={new_sum}  delta={delta:+d}"
            )
            grand["students"] += 1
            grand["old"] += old_sum
            grand["new"] += new_sum

            if not apply:
                continue

            with transaction.atomic():
                cancelled_n = (
                    TrophyEvent.objects
                    .filter(student=s, cancelled_at__isnull=True)
                    .exclude(event_key__startswith="PAPER_COMPLETE:")
                    .update(cancelled_at=timezone.now())
                )
                grand["cancelled"] += cancelled_n

                for (day, paper_id, earned_on, paper) in passing:
                    event_key = f"PAPER_COMPLETE:{s.id}:{day}:{paper_id}"
                    existing = TrophyEvent.objects.filter(
                        event_key=event_key, cancelled_at__isnull=True
                    ).first()
                    if existing is not None:
                        if existing.count == pace and existing.date == earned_on:
                            continue
                        TrophyEvent.objects.filter(id=existing.id).update(cancelled_at=timezone.now())
                    TrophyEvent.objects.create(
                        student=s, event_key=event_key, date=earned_on,
                        reason="PAPER_COMPLETE", pace=pace, base_count=pace,
                        bonus_count=0, count=pace,
                        subject=getattr(paper, "subject", "") or "",
                    )
                    grand["created"] += 1

        self.stdout.write(self.style.SUCCESS(
            f"DONE: students={grand['students']}  created={grand['created']}  "
            f"cancelled={grand['cancelled']}  old_total={grand['old']}  new_total={grand['new']}"
        ))
