"""make_kc_discovery_prompt - print MASTER_KC_DISCOVERY_PROMPT.md with a paper's
ingested questions substituted.

Usage:
    python manage.py make_kc_discovery_prompt <paper_code> [--class N]

Reads the paper's ModelQuestion rows from the DB and prints the discovery
prompt. The AI proposes the KC list; the teacher approves it at the pipeline
gate; seed_kcs remains the sole writer (Rule 10).

Standards: Tatsuoka 1983; Templin & Hoffman 2013; de la Torre & Chiu 2016;
arXiv 2604.16398 (2026); ISO 21500:2021 4.3.3; ISO 9001:2015 7.5.3;
Rule 10; Rule 11; Rule H.
"""
from pathlib import Path as _Path

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

from exams.models import ModelPaper, ModelQuestion


PROMPT_FILE = _Path("/home/orkoworo/idealogy/prompts/MASTER_KC_DISCOVERY_PROMPT.md")


def _subject_from_code(code):
    prefix = (code or "").split("-")[0].upper()
    return {
        "MT": "Mathematics", "PH": "Physics", "CH": "Chemistry",
        "BI": "Biology", "EN": "English", "UR": "Urdu",
        "IS": "Islamiyat", "CS": "Computer Science", "TQ": "Tarjumatul Quran",
    }.get(prefix, "General")


def _format_questions(questions):
    if not questions:
        return "(no questions ingested yet)"
    lines = []
    for q in questions:
        lines.append(str(q.question_index) + ". " + (q.question_text or "")[:600])
    return "\n".join(lines)


class Command(BaseCommand):
    help = "Print MASTER_KC_DISCOVERY_PROMPT.md for one paper."

    def add_arguments(self, parser):
        parser.add_argument("paper_code", type=str)
        parser.add_argument("--class", dest="class_no", type=int, default=9)
        parser.add_argument("--limit", type=int, default=500,
                            help="Max questions to include (default 200).")

    def handle(self, *args, **options):
        code = options["paper_code"].strip().upper()
        class_no = options["class_no"]
        limit = options["limit"]

        if not PROMPT_FILE.exists():
            raise CommandError("Prompt file not found: " + str(PROMPT_FILE))

        paper = ModelPaper.objects.filter(code=code).first()
        if paper is None:
            raise CommandError("ModelPaper not found: " + code)

        questions = list(ModelQuestion.objects.filter(paper=paper)
                         .order_by("question_index")[:limit])
        if not questions:
            raise CommandError("No ModelQuestion rows for paper " + code)

        subject = paper.subject or _subject_from_code(code)

        text = PROMPT_FILE.read_text(encoding="utf-8")
        text = text.replace("__SUBJECT__", subject)
        text = text.replace("__CLASS__", str(class_no))
        text = text.replace("__Q_COUNT__", str(len(questions)))
        text = text.replace("__QUESTIONS__", _format_questions(questions))

        if "__" in text:
            leftovers = [t for t in text.split() if t.startswith("__") and t.endswith("__")]
            if leftovers:
                self.stderr.write("WARN unresolved placeholders: " + ", ".join(set(leftovers)))

        self.stdout.write(text)
