"""Print MASTER_KC_TAG_PROMPT.md with paper questions and KC list substituted.

Usage:
    python manage.py make_kc_tag_prompt <paper_code> [--subject X] [--class N]

Reads the paper's ModelQuestion rows from the DB, prints the prompt that
the AI pastes to produce a Q-matrix JSON. That JSON is then fed to
kc_tag (Rule 10 - kc_tag remains the sole writer).

Standards: Rule 10 (single canonical writer: kc_tag); Rule 11 (prompt
is the printer output); Tatsuoka 1983 (Q-matrix); Templin & Hoffman 2013
(expert judgment primary); AERA/APA/NCME 2014 Std 13.7; ISO 9001:2015
7.5.3 (documented information).
"""
from pathlib import Path as _Path

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

from exams.models import ModelPaper, ModelQuestion, KnowledgeComponent


PROMPT_FILE = _Path("/home/orkoworo/idealogy/prompts/MASTER_KC_TAG_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_kc_list(kcs, subject=""):
    if not kcs:
        return (
            "(NO KCs DEFINED FOR " + (subject.upper() or "THIS SUBJECT") +
            " YET — the KC list for this subject has not been built.\n"
            " Do NOT invent any KC code. For every question, set "
            "primary_kc to \"\" and put a note in reasoning that the KC "
            "list is empty; use confidence <= 0.3.)"
        )
    lines = []
    for kc in kcs:
        lines.append("- " + kc.code + " — " + (kc.title or "") +
                     (" | " + kc.description if kc.description else ""))
    return "\n".join(lines)


def _format_questions(questions):
    if not questions:
        return "(no questions in this paper)"
    lines = []
    for q in questions:
        lines.append("question_index: " + str(q.question_index))
        lines.append("  text: " + (q.question_text or "")[:500])
        lines.append("")
    return "\n".join(lines).rstrip()


class Command(BaseCommand):
    help = "Print MASTER_KC_TAG_PROMPT.md with paper questions and KC list substituted."

    def add_arguments(self, parser):
        parser.add_argument("paper_code", type=str,
                            help="ModelPaper.code (e.g. CH-9-P40 or CH-9)")
        parser.add_argument("--subject", type=str, default=None)
        parser.add_argument("--class", dest="class_no", type=int, default=9)

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

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

        try:
            paper = ModelPaper.objects.get(code=code)
        except ModelPaper.DoesNotExist:
            raise CommandError("ModelPaper not found: " + code)

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

        kcs_qs = KnowledgeComponent.objects.filter(is_active=True)
        if subject and subject != "General":
            kcs_qs = kcs_qs.filter(subject__iexact=subject)
        kcs = list(kcs_qs.order_by("code"))
        # defensive: if subject field is blank on existing rows, fall back by
        # code prefix (C9-CH -> Chemistry) so an old seed does not silently
        # hide the KC list from its true subject.
        if not kcs and subject == "Chemistry":
            kcs = list(KnowledgeComponent.objects
                       .filter(is_active=True, code__startswith="C9-CH")
                       .order_by("code"))

        text = PROMPT_FILE.read_text(encoding="utf-8")
        text = text.replace("__SUBJECT__", subject)
        text = text.replace("__CLASS__", str(class_no))
        text = text.replace("__KC_COUNT__", str(len(kcs)))
        text = text.replace("__KC_LIST__", _format_kc_list(kcs, subject))
        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)
