"""reconcile_modelquestion_dupes - mark legacy duplicate ModelQuestion rows.

Groups rows by (paper_id, question_text). Within each group of size > 1,
the row with the lowest pk is kept as canonical; every other row is
marked by setting superseded_at to the current UTC time. Never deletes.

Standards: Rule 9 (mark, never delete); Rule 10 (one canonical writer
for this transition); Rule 23 (dry-run default, explicit --apply);
Rule 24 (sandbox first); ISO 27001 A.8.15 (append-only change log);
ISO 8000-61 (data quality); AERA/APA/NCME 2014 Std 1.0 (construct
identity is question_text, not question_index);
ISO/IEC/IEEE 29119-3 (deterministic and testable).
"""
from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils import timezone
from django.db.models import Count
from exams.models import ModelQuestion


class Command(BaseCommand):
    help = "Mark legacy duplicate ModelQuestion rows (superseded_at). Never deletes."

    def add_arguments(self, parser):
        parser.add_argument("--apply", action="store_true",
                            help="Actually mark rows (default: dry-run).")

    def handle(self, *args, **opts):
        dry = not opts["apply"]

        groups = (ModelQuestion.objects
                  .values("paper_id", "question_text")
                  .annotate(c=Count("id"))
                  .filter(c__gt=1))

        total_groups = groups.count()
        to_mark = []
        already_marked = 0
        for g in groups:
            rows = list(ModelQuestion.objects
                        .filter(paper_id=g["paper_id"],
                                question_text=g["question_text"])
                        .order_by("pk")
                        .values_list("pk", "superseded_at"))
            keeper_pk = rows[0][0]
            for pk, sup in rows[1:]:
                if sup is not None:
                    already_marked += 1
                else:
                    to_mark.append(pk)

        self.stdout.write("=== duplicate groups ===")
        self.stdout.write("  groups (paper_id, question_text) size>1: " + str(total_groups))
        self.stdout.write("  rows already marked superseded: " + str(already_marked))
        self.stdout.write("  rows to mark on this run: " + str(len(to_mark)))

        if dry:
            self.stdout.write("(DRY RUN - nothing written; pass --apply to mark)")
            return

        now = timezone.now()
        with transaction.atomic():
            for pk in to_mark:
                ModelQuestion.objects.filter(pk=pk).update(superseded_at=now)
        self.stdout.write("Applied: " + str(len(to_mark)) + " rows marked superseded.")
