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

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

The printed text is what the teacher pastes into Gemini (or Claude) to
generate a guided Socratic ladder per surviving misconception. The
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 --ladder-file LFILE

Standards: Polya (1945) four-phase scaffold; Kirschner, Sweller &
Clark (2006) guided > discovery for novices; Sweller et al. (2011)
worked-example effect; Rosenshine (2012) small steps; Hattie &
Timperley (2007) feed-forward; Wood, Bruner & Ross (1976) scaffolding;
Vygotsky (1978) ZPD; AERA/APA/NCME 2014 Std 13.7 (construct naming);
EU AI Act Art.14 (teacher oversight); ISO/IEC 42001 Clause 7.5;
ISO 9001:2015 7.5.3; 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 (
    _clean,
    _float_or_none,
    _int_or_none,
)
from exams.parsing import extract_json


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


def _read_json(path_str, label):
    path = _Path(path_str)
    try:
        raw = path.read_text(encoding="utf-8")
    except FileNotFoundError:
        raise CommandError(label + " file not found: " + str(path))
    try:
        return extract_json(raw)
    except ValueError as exc:
        raise CommandError("Invalid JSON in " + label + " file: " + str(exc))


def _load_pipeline_survivors(generation_file, validation_file, rerank_file):
    gdata = _read_json(generation_file, "Generation")
    vdata = _read_json(validation_file, "Validation")
    rdata = _read_json(rerank_file, "Rerank")

    entries = []
    for c in (gdata.get("candidates") or []):
        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")),
        })
    if not entries:
        raise CommandError("Generation file has no candidates.")

    verdicts = {}
    for v in (vdata.get("validation") or []):
        idx = _int_or_none(v.get("index"))
        if idx is not None:
            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)
    if not survivors:
        raise CommandError("No survivors after validation. Nothing to ladder.")

    ranks = {}
    for r in (rdata.get("ranking") or []):
        idx = _int_or_none(r.get("index"))
        rk = _int_or_none(r.get("rank"))
        if idx is not None and rk is not None:
            ranks[idx] = rk
    for entry in survivors:
        entry["rank"] = ranks.get(entry["index"], 9999)
    survivors.sort(key=lambda e: e["rank"])
    for n, entry in enumerate(survivors, start=1):
        entry["rank"] = n
    return survivors


def _format_survivors(survivors):
    if not survivors:
        return "(none - no survivors after validation and rerank.)"
    lines = []
    for s in survivors:
        lines.append(
            "Candidate " + str(s["index"])
            + " (rank " + str(s["rank"]) + "):")
        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()



def _load_from_kc(kc):
    """Fallback: build the survivors list from kc.misconceptions in DB.

    Applies the same filter as _load_pipeline_survivors: only entries
    with cycle_consistent is True survive; sort by rank then index.
    Standards: Rule 10 (one canonical pipeline); ISO/IEC 42001 7.5;
    Rule 26 (standards above directive).
    """
    stored = kc.misconceptions or []
    survivors = []
    for i, m in enumerate(stored, start=1):
        if not isinstance(m, dict):
            continue
        # cycle_consistent: True = validated; None = pending (accept);
        # False = explicitly rejected by validator (reject).
        # Standards: MISTAKE (Ross & Andreas) - None means unvalidated,
        # not rejected; Rule 26 (standards above directive).
        if m.get("cycle_consistent") is False:
            continue
        survivors.append({
            "index": _int_or_none(m.get("index")) or i,
            "text": _clean(m.get("text")),
            "faulty_reasoning": _clean(m.get("faulty_reasoning")),
            "incorrect_answer": _clean(m.get("incorrect_answer")),
            "confidence": _float_or_none(m.get("confidence")),
            "rank": _int_or_none(m.get("rank")) or 9999,
        })
    if not survivors:
        raise CommandError(
            "No cycle_consistent misconceptions on this KC and no "
            "pipeline files given. Run G4 (generate_kc_content) first.")
    survivors.sort(key=lambda e: (e["rank"], e["index"]))
    for n, e in enumerate(survivors, start=1):
        e["rank"] = n
    return survivors


class Command(BaseCommand):
    help = "Print MASTER_KC_SOCRATIC_LADDER_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, default=None,
                            help="Optional. Path to Gemini MISTAKE triples JSON. "
                                 "If omitted, reads kc.misconceptions from DB.")
        parser.add_argument("--validation-file", dest="validation_file",
                            type=str, default=None,
                            help="Optional. ChatGPT verdicts JSON (with --generation-file).")
        parser.add_argument("--rerank-file", dest="rerank_file",
                            type=str, default=None,
                            help="Optional. Claude rerank JSON (with --generation-file).")

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

        if generation_file and validation_file and rerank_file:
            survivors = _load_pipeline_survivors(
                generation_file, validation_file, rerank_file)
        elif generation_file or validation_file or rerank_file:
            raise CommandError(
                "Provide all three pipeline files, or none (to read from DB).")
        else:
            survivors = _load_from_kc(kc)

        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)
