"""Print MASTER_KC_VALIDATION_PROMPT.md with KC and candidates substituted.

Usage:
    python manage.py make_kc_validation_prompt <kc_code> --generation-file FILE

The printed text is what the teacher pastes into ChatGPT (a different
model family from Gemini). ChatGPT's JSON reply is saved and fed back via:

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

Standards: MISTAKE (Ross & Andreas, arXiv 2510.11502) cycle consistency;
Finch-Zk (Goel et al., EMNLP 2025) cross-model checking;
NIST AI RMF GOVERN 6.1 (independent model review);
NIST AI RMF MEASURE 2.5 (schema validation before acceptance);
ISO/IEC 42001 Clause 7.5 (prompt as documented information);
ISO 9001:2015 7.5.3 (control of documented information);
Rule 11 (prompt mandatory). Prompt file is prod-only config.
"""
from pathlib import Path as _Path

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

from exams.models import KnowledgeComponent
from exams.management.commands.generate_kc_content import (
    Command as GenCmd,
    _clean,
    _float_or_none,
)
from exams.parsing import extract_json


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


def _format_candidates(candidates):
    if not candidates:
        return "(none - no candidates to validate. Provide a generation file first.)"
    lines = []
    for i, c in enumerate(candidates, start=1):
        lines.append("Candidate " + str(i) + ":")
        lines.append("  misconception:     " + _clean(c.get("text")))
        lines.append("  faulty_reasoning:  " + _clean(c.get("faulty_reasoning")))
        lines.append("  incorrect_answer:  " + _clean(c.get("incorrect_answer")))
        conf = c.get("confidence")
        lines.append("  confidence:        " + (str(conf) if conf is not None else "(none)"))
        lines.append("")
    return "\n".join(lines).rstrip()


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

    def add_arguments(self, parser):
        parser.add_argument("kc_code", type=str,
                            help="KnowledgeComponent.code to print the prompt for.")
        parser.add_argument("--generation-file", dest="generation_file",
                            type=str, required=True,
                            help="Path to JSON file with Gemini MISTAKE triples.")

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

        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)

        gpath = _Path(generation_file)
        try:
            raw = gpath.read_text(encoding="utf-8")
        except FileNotFoundError:
            raise CommandError("Generation file not found: " + str(gpath))
        try:
            data = extract_json(raw)
        except ValueError as exc:
            raise CommandError("Invalid JSON in generation file: " + str(exc))

        raw_candidates = data.get("candidates") or []
        if not raw_candidates:
            raise CommandError("Generation file has no candidates.")

        entries = []
        for c in raw_candidates:
            entries.append({
                "text": _clean(c.get("misconception")),
                "faulty_reasoning": _clean(c.get("faulty_reasoning")),
                "incorrect_answer": _clean(c.get("incorrect_answer")),
                "confidence": _float_or_none(c.get("confidence")),
            })

        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_SUBJECT__", kc.subject or "")
        text = text.replace("__KC_CHAPTER__", kc.chapter or "")
        text = text.replace("__KC_COGNITIVE_LEVEL__", kc.cognitive_level or "(unspecified)")
        text = text.replace("__KC_DESCRIPTION__", kc.description or "(no description)")
        text = text.replace("__CANDIDATES__", _format_candidates(entries))

        self.stdout.write(text)
