"""rps_sync - feed Exam/Submission results back into RPSItem state.

Design: design/RPS-DESIGN-v1.1.md Section 5 + ERRATA E2.
Standards: Leitner 1972; SM-2 (Wozniak 1987); FSRS 2022-24;
  Keller 1968 PSI (mastery = 3 consecutive); Bloom 1968;
  MTSS/DBI NCII; Sweller; AERA/APA/NCME 2014 Std 1.0, 13.7.
Rule 10: rps_sync is the sole writer of RPSAttempt and the sole updater
of RPSItem state after seed. ingest_reports remains the sole writer of
Exam/Submission (this command is read-only against those tables).

Usage:
    python manage.py rps_sync --day YYYY-MM-DD
    python manage.py rps_sync --day YYYY-MM-DD --dry-run
"""
from datetime import datetime, timedelta
from decimal import Decimal

from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from django.db import transaction

from exams.models import Exam, Submission, RPSItem, RPSAttempt
from exams.rps_advance import apply_outcome as _apply_outcome  # DOHRAI-2 (Rule 10 single source of truth)


MASTERY_HITS = 3
EASE_CAP = 3.0
EASE_FLOOR = 1.3
EASE_UP = 0.05
EASE_DOWN = 0.15


def _parse_day(s):
    try:
        return datetime.strptime(s, "%Y-%m-%d").date()
    except ValueError:
        raise CommandError("--day must be YYYY-MM-DD, got: " + s)


def _outcome_from_submission(sub, exam):
    """Map an ingested Submission to CORRECT/PARTIAL/WRONG/SKIPPED.

    Uses the band stored in sub.ai_raw (v4.0+ grading prompt) if present;
    otherwise falls back to ai_score / exam.max_marks ratio. SKIPPED when
    ai_score is null or zero AND there is no ai_raw band.
    """
    band = ""
    try:
        raw = sub.ai_raw or {}
        band = (raw.get("band") or "").strip()
    except Exception:
        band = ""
    if band in ("Excellent", "Good"):
        return "CORRECT"
    if band in ("Fair",):
        return "PARTIAL"
    if band in ("Below Average", "Poor"):
        return "WRONG"
    if band == "Not Attempted":
        return "SKIPPED"

    # Fallback: ratio
    if sub.ai_score is None:
        return "SKIPPED"
    max_marks = exam.max_marks or Decimal("5")
    if max_marks == 0:
        return "SKIPPED"
    ratio = float(sub.ai_score) / float(max_marks)
    if ratio >= 0.75:
        return "CORRECT"
    if ratio >= 0.50:
        return "PARTIAL"
    if ratio > 0:
        return "WRONG"
    return "SKIPPED"


def _apply_outcome(item, outcome, day):
    """Deprecated alias -> exams.rps_advance.apply_outcome (Rule 10, DOHRAI-2)."""
    return _apply_outcome(item, outcome, day)

class Command(BaseCommand):
    help = "Feed today's Exam/Submission results back into RPSItem state."

    def add_arguments(self, parser):
        parser.add_argument("--day", type=str, required=True)
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **options):
        day = _parse_day(options["day"])
        dry = options["dry_run"]

        # 1. Exams for the day that carry an RPS link
        exams = (Exam.objects
                 .filter(exam_date=day, model_question__isnull=False)
                 .select_related("student", "model_question"))
        total_exams = exams.count()
        self.stdout.write("Exams with RPS link on " + str(day) + ": " + str(total_exams))

        linked = 0
        unmatched = 0
        no_sub = 0
        outcomes = {"CORRECT": 0, "PARTIAL": 0, "WRONG": 0, "SKIPPED": 0}

        with transaction.atomic():
            for exam in exams:
                sub = Submission.objects.filter(exam=exam).first()
                if sub is None:
                    no_sub += 1
                    continue
                item = (RPSItem.objects
                        .filter(student=exam.student,
                                model_question_id=exam.model_question_id)
                        .first())
                if item is None:
                    unmatched += 1
                    continue

                outcome = _outcome_from_submission(sub, exam)
                outcomes[outcome] += 1

                if dry:
                    self.stdout.write("[dry] " + exam.student.code
                                      + " mq=" + str(exam.model_question_id)
                                      + " outcome=" + outcome
                                      + " item=" + str(item.id))
                else:
                    # write attempt log
                    RPSAttempt.objects.create(
                        item=item,
                        attempted_at=timezone.now(),
                        response_kind="PAPER_TEST",
                        outcome=outcome,
                        source="INGEST_PIPELINE",
                        exam=exam,
                        submission=sub,
                        note="",
                    )
                    # update item state
                    _apply_outcome(item, outcome, day)
                    item.save(update_fields=[
                        "current_interval_days", "current_ease",
                        "consecutive_correct", "lapsed_count",
                        "mastery_state", "last_attempted_at", "next_due_at",
                    ])
                linked += 1

        self.stdout.write("linked:    " + str(linked))
        self.stdout.write("unmatched: " + str(unmatched) + "  (Exam.model_question has no RPSItem — RPSItem not seeded for that student/mq)")
        self.stdout.write("no_sub:    " + str(no_sub) + "  (Exam has no Submission yet)")
        self.stdout.write("outcomes:  " + str(outcomes))
        if dry:
            self.stdout.write("(DRY RUN - nothing written)")
