"""rps_print_sheet - render today's RPSSchedule as a printable test sheet.

Read-only. Does NOT write to the database. rps_select remains the sole
writer of RPSSchedule (Rule 10).

Design: design/RPS-DESIGN-v1.1.md + ERRATA.
Standards: ISO 9001:2015 8.5.1 (traceability); AERA/APA/NCME 2014 Std 1.0
(construct naming via model_question_slug); Section 15.4 (no teacher typing);
Rule 10 (read-only; does not write).

Usage:
    python manage.py rps_print_sheet --day YYYY-MM-DD
    python manage.py rps_print_sheet --day YYYY-MM-DD --student S-0017
    python manage.py rps_print_sheet --day YYYY-MM-DD --out FILE
"""
from datetime import datetime

from django.core.management.base import BaseCommand, CommandError

from exams.models import RPSSchedule, RPSItem


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)


class Command(BaseCommand):
    help = "Print today's RPS schedule as a test sheet (read-only)."

    def add_arguments(self, parser):
        parser.add_argument("--day", type=str, required=True)
        parser.add_argument("--student", type=str, default=None)
        parser.add_argument("--out", type=str, default=None,
                            help="Write to FILE instead of stdout.")

    def handle(self, *args, **options):
        day = _parse_day(options["day"])
        code = options["student"]
        out_path = options["out"]

        qs = RPSSchedule.objects.filter(day=day).select_related("student")
        if code:
            qs = qs.filter(student__code=code)
        rows = list(qs.order_by("student__code"))
        if not rows:
            self.stdout.write("No RPSSchedule rows for " + str(day) + ". Run rps_select first.")
            return

        lines = []
        lines.append("=" * 72)
        lines.append("IDEALOGY - RETRIEVAL TEST SHEET")
        lines.append("Day: " + str(day))
        lines.append("Students: " + str(len(rows)))
        lines.append("=" * 72)
        lines.append("")

        # Master manifest (paste into MASTER_GRADING_PROMPT v6.0 STUDENT CONTEXT)
        lines.append("# ---- REFERENCE MANIFEST (for prompt v6.0; do not print for students) ----")
        for r in rows:
            lines.append("# " + r.student.code + " (tier cap=" + str(r.cap_items) + ")")
            item_ids = r.item_ids or []
            items = {i.id: i for i in RPSItem.objects.filter(id__in=item_ids).select_related("model_question")}
            for idx, iid in enumerate(item_ids, start=1):
                it = items.get(iid)
                if not it:
                    continue
                slug = it.model_question.question_slug if it.model_question else ""
                lines.append("#   Q" + str(iid) + "  " + (slug or "(no slug)"))
            lines.append("#")
        lines.append("")

        # Per-student test sheet
        for r in rows:
            lines.append("=" * 72)
            lines.append("STUDENT: " + r.student.code + " | day " + str(day)
                         + " | items " + str(r.produced_count) + "/" + str(r.cap_items))
            lines.append("=" * 72)
            item_ids = r.item_ids or []
            items = {i.id: i for i in RPSItem.objects.filter(id__in=item_ids).select_related("model_question")}
            for iid in item_ids:
                it = items.get(iid)
                if not it:
                    continue
                mq = it.model_question
                qtext = (mq.question_text if mq else "") or ""
                subject = ""
                try:
                    subject = mq.paper.subject if mq and mq.paper else ""
                except Exception:
                    subject = ""
                lines.append("Q" + str(iid) + ". [" + (subject or "-") + "] " + qtext)
                lines.append("")
            lines.append("")

        text = "\n".join(lines)
        if out_path:
            import os as _os
            _parent = _os.path.dirname(out_path)
            if _parent:
                _os.makedirs(_parent, exist_ok=True)
            with open(out_path, "w", encoding="utf-8") as f:
                f.write(text)
            self.stdout.write("wrote " + out_path + " (" + str(len(text)) + " bytes)")
        else:
            self.stdout.write(text)
