"""Print MASTER_KC_RERANK_PROMPT.md with KC and survivors substituted.

Usage:
    python manage.py make_kc_rerank_prompt <kc_code> \
        --generation-file GFILE --validation-file VFILE

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

    python manage.py generate_kc_content <kc_code> \
        --generation-file GFILE --validation-file VFILE --rerank-file RFILE

Standards: MiRAGE (2025) cross-attention reranking (removing the
Reranker drops MAP@1 by 23%); ITU-T F.748.52 (RAG optimization);
Azure Architecture Center (cross-encoder, relative scores);
ISO 9001:2015 7.5.3 (documented information);
ISO/IEC 42001 (RAG pipeline components documented);
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_RERANK_PROMPT.md")


def _load_candidates(generation_file, validation_file):
    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")),
        })

    vpath = _Path(validation_file)
    try:
        vraw = vpath.read_text(encoding="utf-8")
    except FileNotFoundError:
        raise CommandError("Validation file not found: " + str(vpath))
    try:
        vdata = extract_json(vraw)
    except ValueError as exc:
        raise CommandError("Invalid JSON in validation file: " + str(exc))

    verdicts = {}
    for v in (vdata.get("validation") or []):
        try:
            idx = int(v.get("index"))
        except (TypeError, ValueError):
            continue
        verdicts[idx] = bool(v.get("cycle_consistent"))

    survivors = []
    for i, entry in enumerate(entries, start=1):
        if verdicts.get(i):
            entry["index"] = i
            survivors.append(entry)
    return survivors


def _format_survivors(survivors):
    if not survivors:
        return "(none - no survivors to rank. Provide a validation file with at least one cycle_consistent=True entry.)"
    lines = []
    for s in survivors:
        lines.append("Candidate " + str(s["index"]) + ":")
        lines.append("  misconception:     " + s["text"])
        lines.append("  faulty_reasoning:  " + s["faulty_reasoning"])
        lines.append("  incorrect_answer:  " + s["incorrect_answer"])
        lines.append("")
    return "\n".join(lines).rstrip()


class Command(BaseCommand):
    help = "Print MASTER_KC_RERANK_PROMPT.md with KC and survivors 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.")
        parser.add_argument("--validation-file", dest="validation_file",
                            type=str, required=True,
                            help="Path to JSON file with ChatGPT verdicts.")

    def handle(self, *args, **options):
        kc_code = options["kc_code"]
        generation_file = options["generation_file"]
        validation_file = options["validation_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)

        survivors = _load_candidates(generation_file, validation_file)
        if not survivors:
            raise CommandError(
                "No survivors after validation. Nothing to rerank.")

        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("__SURVIVORS__", _format_survivors(survivors))

        self.stdout.write(text)
