"""seed_rps_items - populate RPSItem rows for one student or all.

Design: design/RPS-DESIGN-v1.1.md
Standards: Keller 1968 PSI; Bloom 1968; MTSS/DBI (NCII) tier-driven
starting state; Leitner 1972; SM-2 (Wozniak 1987); FSRS 2022-24.
Rule 10: this command is the sole writer of RPSItem during the seed
phase. rps_sync (Phase 4) will be the sole writer during update.

Usage:
    python manage.py seed_rps_items --student S-0001
    python manage.py seed_rps_items --all
    python manage.py seed_rps_items --all --limit 50 --dry-run
"""
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

from exams.models import Student, ModelQuestion, RPSItem


# Per RPS-DESIGN-v1.1.md Section 5.2
TIER_START = {
    1: {"interval": 3, "ease": 2.5},
    2: {"interval": 3, "ease": 2.5},
    3: {"interval": 2, "ease": 2.3},
    4: {"interval": 1, "ease": 2.0},
    5: {"interval": 1, "ease": 1.7},
}


def _tier_of(student):
    for attr in ("tier", "tier_level", "tier_num"):
        v = getattr(student, attr, None)
        try:
            n = int(v)
            if 1 <= n <= 5:
                return n
        except (TypeError, ValueError):
            pass
    return 3


class Command(BaseCommand):
    help = "Seed RPSItem rows for a student or all students."

    def add_arguments(self, parser):
        parser.add_argument("--student", type=str, default=None)
        parser.add_argument("--all", action="store_true")
        parser.add_argument("--limit", type=int, default=None)
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **options):
        code = options["student"]
        do_all = options["all"]
        limit = options["limit"]
        dry = options["dry_run"]

        if not code and not do_all:
            raise CommandError("Provide --student CODE or --all.")

        if code:
            try:
                students = [Student.objects.get(code=code)]
            except Student.DoesNotExist:
                raise CommandError("Student not found: " + code)
        else:
            try:
                students = list(Student.objects.filter(is_active=True).order_by("code"))
            except Exception:
                students = list(Student.objects.order_by("code"))
            if not students:
                students = list(Student.objects.order_by("code"))

        if not students:
            self.stdout.write("No students selected.")
            return

        qs = ModelQuestion.objects.exclude(kc_code="").order_by("paper_id", "question_index")
        total_q = qs.count()
        self.stdout.write("ModelQuestions with kc_code: " + str(total_q))
        if total_q == 0:
            self.stdout.write("EMPTY: no tagged questions. Feed the KC pipeline first (design v1.1 Section 6.1).")
            return

        today = date.today()
        created_total = 0
        skipped_total = 0

        for s in students:
            tier = _tier_of(s)
            start = TIER_START[tier]
            existing_qids = set(
                RPSItem.objects.filter(student=s).values_list("model_question_id", flat=True)
            )
            bulk = []
            for mq in qs.iterator():
                if mq.id in existing_qids:
                    skipped_total += 1
                    continue
                if limit and len(bulk) >= limit:
                    break
                bulk.append(RPSItem(
                    student=s,
                    kc_code=mq.kc_code or "",
                    model_question=mq,
                    next_due_at=today,
                    current_interval_days=start["interval"],
                    current_ease=start["ease"],
                    consecutive_correct=0,
                    lapsed_count=0,
                    mastery_state="LEARNING",
                ))
            if dry:
                self.stdout.write("[dry] " + s.code + " tier=" + str(tier)
                                  + ": would create " + str(len(bulk)) + " items")
            else:
                with transaction.atomic():
                    RPSItem.objects.bulk_create(bulk, ignore_conflicts=True)
                self.stdout.write(s.code + " tier=" + str(tier)
                                  + ": created " + str(len(bulk)) + " items")
            created_total += len(bulk)

        self.stdout.write("--- total: " + str(created_total) + " created, "
                          + str(skipped_total) + " already existing")
        if dry:
            self.stdout.write("(DRY RUN - nothing written)")
