"""Print MASTER_KC_MISCONCEPTION_PROMPT.md with KnowledgeComponent data substituted.

Usage:
    python manage.py make_kc_prompt <kc_code>

The printed text is what the teacher pastes into Gemini (Search ON) to
generate MISTAKE triples. Gemini's JSON reply is saved to a file and fed
back via:

    python manage.py generate_kc_content <kc_code> --generation-file FILE

Standards: MISTAKE (Ross & Andreas, arXiv 2510.11502) triple structure;
ISO 9001:2015 7.5.3 (documented information); ISO/IEC 42001 Clause 7.5
(prompt as production configuration); Rule 11 (prompt is part of the
instruction, not a separate task). Prompt file is prod-only config.
"""
from pathlib import Path as _Path

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

from exams.management.commands.generate_kc_content import Command as GenCmd
from exams.models import KnowledgeComponent, ModelQuestion


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


def _format_questions(questions):
    if not questions:
        return ("(none - this KC has no linked ModelQuestion rows yet. "
                "Generate candidates from the KC description alone, and "
                "note in each triple's source that no context was available.)")
    lines = []
    for q in questions:
        lines.append(
            "Q" + str(q["question_index"])
            + " [" + q["paper_code"] + "]"
            + " (marks=" + str(q["marks"])
            + ", newman=" + (q["newman_focus"] or "-")
            + ", chapter=" + (q["chapter"] or "-") + ")")
        lines.append("  Question: " + q["question_text"])
        lines.append("  Model answer: " + q["model_answer"])
        rc = q.get("reasoning_chain") or []
        if rc:
            lines.append("  Reasoning chain: " + " | ".join(str(s) for s in rc))
        else:
            lines.append("  Reasoning chain: (none)")
        lines.append("")
    return "\n".join(lines).rstrip()


class Command(BaseCommand):
    help = "Print MASTER_KC_MISCONCEPTION_PROMPT.md with KC and context substituted."

    def add_arguments(self, parser):
        parser.add_argument("kc_code", type=str,
                            help="KnowledgeComponent.code to print the prompt for.")
        parser.add_argument("--limit", type=int, default=10,
                            help="Max ModelQuestion rows to include as context.")

    def handle(self, *args, **options):
        kc_code = options["kc_code"]
        limit = options["limit"]

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

        try:
            kc = KnowledgeComponent.objects.get(code=kc_code)
        except KnowledgeComponent.DoesNotExist:
            raise CommandError("KnowledgeComponent not found: " + kc_code)

        qs = ModelQuestion.objects.filter(kc_code=kc_code, superseded_at__isnull=True)[:limit]
        questions = GenCmd()._retrieve(None, qs)

        text = PROMPT_FILE.read_text(encoding="utf-8")
        text = text.replace("__KC_CODE__", kc.code)
        text = text.replace("__KC_TITLE__", kc.title or "")
        text = text.replace("__KC_DESCRIPTION__", kc.description or "(no description)")
        text = text.replace("__SUBJECT__", kc.subject or "")
        text = text.replace("__CHAPTER__", kc.chapter or "")
        text = text.replace("__COGNITIVE_LEVEL__", kc.cognitive_level or "UND")
        text = text.replace("__CONTEXT_QUESTIONS__", _format_questions(questions))

        self.stdout.write(text)
