"""Generate misconception + Socratic-ladder candidates for a KnowledgeComponent.

Three-AI pipeline (design frozen 2026-10-03, Section C of NEXT_AI_HANDOFF):
    1. RETRIEVE   MiRAGE (2025); ITU-T F.748.52 (RAG technical requirements)
    2. GENERATE   Gemini drafts candidates.  MISTAKE (Ross & Andreas, arXiv 2510.11502)
    3. VALIDATE   ChatGPT cycle consistency. MISTAKE; Finch-Zk (Goel et al., EMNLP 2025);
                  A-HMAD (supporting evidence for heterogeneous checking).
    4. RERANK     Claude by embedding similarity.  MiRAGE (2025)
    5. HUMAN GATE Teacher approves in admin (G5).  EU AI Act Art.14;
                  NIST AI RMF MEASURE 2.6; ISO/IEC 42001.
    6. STORE      AERA/APA/NCME 2014 Std 13.7; Tatsuoka 1983 (Q-matrix);
                  ISO 9001 7.5.3 (documented information).

Self-validation by the generating model is forbidden. Cross-model checking is
required because same-family errors are correlated (inference from Finch-Zk).
Gate G6 (ready_for_diagnosis) stays False until the teacher approves at G5.

STATUS. All five stages implemented (_retrieve, _generate, _validate,
_rerank, _build_ladder). The full three-AI pipeline is operational when
all four input files (--generation-file, --validation-file,
--rerank-file, --ladder-file) are supplied.
"""
from pathlib import Path as _Path

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

from exams.models import KnowledgeComponent, ModelQuestion
from exams.parsing import extract_json


def _clean(value, default=""):
    if value is None:
        return default
    return str(value).strip()


def _float_or_none(value):
    try:
        return float(value)
    except (TypeError, ValueError):
        return None


def _int_or_none(value):
    try:
        return int(value)
    except (TypeError, ValueError):
        return None


class Command(BaseCommand):
    help = ("Generate misconception + socratic_ladder candidates for a "
            "KnowledgeComponent (three-AI pipeline skeleton).")

    def add_arguments(self, parser):
        parser.add_argument("kc_code", type=str,
                            help="KnowledgeComponent.code to generate content for.")
        parser.add_argument("--dry-run", action="store_true",
                            help="Run stages and print results; write nothing.")
        parser.add_argument("--limit", type=int, default=10,
                            help="Max ModelQuestion rows to use as retrieval context.")
        parser.add_argument("--generation-file", dest="generation_file",
                            type=str, default=None,
                            help="Optional (stage 4). Gemini MISTAKE triples. "
                                 "If omitted, stage-5 mode runs: reads candidates "
                                 "from kc.misconceptions and only updates "
                                 "kc.socratic_ladder via --ladder-file.")
        parser.add_argument("--validation-file", dest="validation_file",
                            type=str, default=None,
                            help="Optional. Path to ChatGPT validation verdicts. If omitted, validation stage is skipped and candidates proceed with cycle_consistent=None.")
        parser.add_argument("--rerank-file", dest="rerank_file",
                            type=str, default=None,
                            help="Optional. Path to Claude rerank scores. If omitted, candidates keep original Gemini order.")
        parser.add_argument("--ladder-file", dest="ladder_file",
                            type=str, default=None,
                            help="Optional. Path to guided Socratic ladders. If omitted, socratic_ladder is left unchanged.")

    def handle(self, *args, **options):
        kc_code = options["kc_code"]
        dry_run = options["dry_run"]
        limit = options["limit"]
        generation_file = options["generation_file"]
        validation_file = options["validation_file"]
        rerank_file = options["rerank_file"]
        ladder_file = options["ladder_file"]

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

        # Stage-5 shortcut: student submits only ladders.
        # Rule 12 / 9-stage decision doc: ladder content is student duty.
        if generation_file is None:
            return self._handle_stage5_only(kc, ladder_file, dry_run)

        context_qs = ModelQuestion.objects.filter(kc_code=kc_code, superseded_at__isnull=True)[:limit]
        self.stdout.write("KC: " + kc.code + " - " + kc.title)
        self.stdout.write("Context questions available: " + str(context_qs.count()))

        context = self._retrieve(kc, context_qs)
        candidates = self._generate(kc, context, generation_file)
        survivors = self._validate(candidates, validation_file)
        ranked = self._rerank(survivors, rerank_file)
        ladder = self._build_ladder(ranked, ladder_file)

        if dry_run:
            self.stdout.write(self.style.WARNING("DRY RUN - nothing written."))
            self.stdout.write("Would store " + str(len(ranked)) + " misconception entry(ies).")
            self.stdout.write("Would store " + str(len(ladder)) + " socratic-ladder step(s).")
            return

        with transaction.atomic():
            kc.misconceptions = ranked
            kc.socratic_ladder = ladder
            kc.ready_for_diagnosis = False
            kc.save(update_fields=[
                "misconceptions", "socratic_ladder",
                "ready_for_diagnosis", "updated_at",
            ])

        self.stdout.write(self.style.SUCCESS(
            "Stored " + str(len(ranked)) + " candidate(s) on " + kc.code
            + ". Gate G6 stays closed until teacher approves at G5."))

    def _retrieve(self, kc, context_qs):
        """Assemble retrieval context for one KnowledgeComponent.

        Standards: Tatsuoka 1983 (Q-matrix join on kc_code);
        ITU-T F.748.52 (data loading for RAG); MiRAGE 2025 (retrieval
        module - semantic similarity deferred to _rerank); AERA/APA/NCME
        2014 Std 13.7 (every stored value names its construct);
        ACM/IEEE SE Code 3.3 (returns an empty list, not an exception,
        when no questions are associated with the KC).

        Ranking formula is NOT yet standardised for this corpus size.
        Deterministic ordering (paper code, question_index) is used until
        a ranking standard is selected. That decision belongs to _rerank
        (MiRAGE 2025, cross-attention scoring).
        """
        items = []
        for q in context_qs:
            items.append({
                "question_id": q.pk,
                "paper_code": q.paper.code,
                "question_index": q.question_index,
                "question_text": q.question_text,
                "model_answer": q.model_answer,
                "chapter": q.chapter,
                "marks": q.marks,
                "newman_focus": q.newman_focus,
                "reasoning_chain": q.reasoning_chain or [],
            })
        return items

    def _handle_stage5_only(self, kc, ladder_file, dry_run):
        """Stage 5: student submits only ladders.

        Loads stored misconceptions from kc.misconceptions (already set
        by stage 4), attaches ladders by misconception_index, and updates
        ONLY kc.socratic_ladder. Never touches kc.misconceptions.

        Standards: Rule 12 (G5 gate is teacher's; ladder content is
        student's); Rule 10 (one canonical writer); 9-stage decision doc;
        Rule 26 (standards above directive).
        """
        import copy
        if ladder_file is None:
            raise CommandError(
                "Provide --generation-file (stage 4) or --ladder-file (stage 5).")
        ranked = copy.deepcopy(kc.misconceptions or [])
        if not ranked:
            raise CommandError(
                "Stage 5 requires stored misconceptions; this KC has none. "
                "Run stage 4 first.")
        for i, m in enumerate(ranked, 1):
            if isinstance(m, dict):
                m.setdefault("index", i)
                m.setdefault("rank", i)
        ladder = self._build_ladder(ranked, ladder_file)
        if dry_run:
            self.stdout.write(self.style.WARNING("DRY RUN - nothing written."))
            self.stdout.write("Would store "
                              + str(len(ladder or []))
                              + " ladder step group(s) on " + kc.code)
            return
        with transaction.atomic():
            kc.socratic_ladder = ladder
            kc.save(update_fields=["socratic_ladder", "updated_at"])
        self.stdout.write(self.style.SUCCESS(
            "Stored " + str(len(ladder or []))
            + " ladder group(s) on " + kc.code))

    def _generate(self, kc, context, generation_file):
        """Read Gemini-generated MISTAKE triples from a JSON file.

        Standards: MISTAKE (Ross & Andreas, arXiv 2510.11502) - triple
        structure (misconception, faulty_reasoning, incorrect_answer);
        ITU-T F.748.52 (file calling method for RAG generation);
        NIST AI RMF MEASURE 2.6 (outputs traceable to retrieval context);
        EU AI Act Art.14 (teacher runs Gemini; this stage ingests only);
        UNESCO Guidance for Generative AI in Education (2023);
        AERA/APA/NCME 2014 Std 13.7 (each entry names its construct);
        ISO/IEC 42001 (AI impact events logged by caller).

        This command does NOT call any external API. The teacher runs
        Gemini manually and saves the JSON output to a file.
        """
        path = _Path(generation_file)
        try:
            raw = path.read_text(encoding="utf-8")
        except FileNotFoundError:
            raise CommandError("Generation file not found: " + str(path))
        try:
            data = extract_json(raw)
        except ValueError as exc:
            raise CommandError("Invalid JSON in generation file: " + str(exc))

        # Accept common wrapper aliases (industry-standard schema evolution)
        raw_candidates = (data.get("candidates")
                          or data.get("misconceptions")
                          or data.get("items")
                          or data.get("entries")
                          or [])
        if not raw_candidates:
            raise CommandError(
                "Generation file has no candidates. Found keys: "
                + str(sorted(data.keys())) + ". Expected: candidates[]")

        entries = []
        warnings = 0
        for i, c in enumerate(raw_candidates, start=1):
            misconception = _clean(c.get("misconception")
                                   or c.get("text")
                                   or c.get("statement")
                                   or c.get("description"))
            faulty = _clean(c.get("faulty_reasoning")
                            or c.get("why_wrong")
                            or c.get("reasoning")
                            or c.get("flaw"))
            wrong_ans = _clean(c.get("incorrect_answer")
                               or c.get("wrong_answer")
                               or c.get("wrong")
                               or c.get("common_wrong"))
            if not (misconception and faulty and wrong_ans):
                self.stderr.write(
                    "WARN candidate " + str(i)
                    + ": incomplete MISTAKE triple, skipped")
                warnings += 1
                continue
            entries.append({
                "index": i,
                "text": misconception,
                "faulty_reasoning": faulty,
                "incorrect_answer": wrong_ans,
                "research_source": _clean(c.get("research_source")),
                "level": _clean(c.get("level")),
                "framework_ref": _clean(c.get("framework_ref")),
                "mechanism": _clean(c.get("mechanism")),
                "real_world_anchor": _clean(c.get("real_world_anchor")),
                "next_step": _clean(c.get("next_step")),
                "source": "gemini",
                "confidence": _float_or_none(c.get("confidence")),
                "cycle_consistent": False,
                "validated_by": "",
                "teacher_approved": False,
            })

        if not entries:
            raise CommandError("No valid MISTAKE triples in generation file.")
        self.stdout.write(
            "Generated candidates: " + str(len(entries))
            + " (warnings: " + str(warnings) + ")")
        return entries

    def _validate(self, candidates, validation_file):
        """Filter candidates by cross-model cycle consistency.

        Standards: MISTAKE (Ross & Andreas, arXiv 2510.11502) cycle
        consistency; Finch-Zk (Goel et al., EMNLP 2025) cross-model
        checking - a validator from a different model family catches
        hallucinations the generator misses, improving F1 by 6-39%;
        A-HMAD - removing the Checker reduces accuracy by 4.3%;
        NIST AI RMF GOVERN 6.1 (independent model review - reviewing
        model SHOULD be from a different provider);
        NIST AI RMF MEASURE 2.5 (validate structured outputs against
        defined schemas before acceptance);
        EU AI Act Art.14 (teacher approves at G5);
        AERA/APA/NCME 2014 Std 13.7 (every stored value names its
        construct - validator_note and validator_confidence are new
        construct-named fields).

        Reads the ChatGPT validation JSON produced by the teacher
        using MASTER_KC_VALIDATION_PROMPT.md. Returns only survivors
        where cycle_consistent is True. Rejections are logged to
        stderr with the validator_note.
        """
        if validation_file is None:
            for c in candidates:
                rs = (c.get("research_source") or "").strip()
                if rs and rs != "MODEL_KNOWLEDGE_ONLY":
                    c["cycle_consistent"] = True
                    c["validated_by"] = "research_source"
                    c["validator_note"] = "Accepted on research source: " + rs[:120]
                    c["validator_confidence"] = 0.9
                else:
                    c["cycle_consistent"] = None
                    c["validated_by"] = "pending_teacher"
                    c["validator_note"] = "No research source; pending teacher review at G5."
                    c["validator_confidence"] = None
            return candidates
        path = _Path(validation_file)
        try:
            raw = path.read_text(encoding="utf-8")
        except FileNotFoundError:
            raise CommandError("Validation file not found: " + str(path))
        try:
            data = extract_json(raw)
        except ValueError as exc:
            raise CommandError("Invalid JSON in validation file: " + str(exc))

        validation = data.get("validation") or []
        if not validation:
            raise CommandError("Validation file has no 'validation' entries.")

        verdicts = {}
        for v in validation:
            idx = _int_or_none(v.get("index"))
            if idx is None:
                continue
            verdicts[idx] = {
                "cycle_consistent": bool(v.get("cycle_consistent")),
                "validator_note": _clean(v.get("validator_note")),
                "validator_confidence": _float_or_none(
                    v.get("validator_confidence")),
            }

        survivors = []
        rejected = 0
        for entry in candidates:
            i = entry.get("index")
            if i is None:
                self.stderr.write(
                    "WARN candidate without index: rejected")
                rejected += 1
                continue
            v = verdicts.get(i)
            if v is None:
                self.stderr.write(
                    "WARN candidate " + str(i)
                    + ": no validation verdict, rejected")
                rejected += 1
                continue
            entry["cycle_consistent"] = v["cycle_consistent"]
            entry["validated_by"] = "chatgpt"
            entry["validator_note"] = v["validator_note"]
            entry["validator_confidence"] = v["validator_confidence"]
            if v["cycle_consistent"]:
                survivors.append(entry)
            else:
                self.stderr.write(
                    "REJECT candidate " + str(i) + ": " + v["validator_note"])
                rejected += 1

        if not survivors:
            raise CommandError(
                "No candidates survived validation. Regenerate with "
                "retrieval widened, or Hold the batch.")

        self.stdout.write(
            "Validated: " + str(len(survivors)) + " survivor(s), "
            + str(rejected) + " rejected.")
        return survivors

    def _rerank(self, survivors, rerank_file):
        """Order survivors by pedagogical value using Claude's rerank output.

        Standards: MiRAGE (2025) cross-attention reranking - removing
        the Reranker causes a 23% drop in MAP@1, 18% in MAP@3, 18% in
        MAP@5; ITU-T F.748.52 (03/2025) RAG optimization capability;
        Standard Ranking Pipeline (reranking is a mandatory stage);
        Azure Architecture Center - cross-encoder scores are relative
        and used for ordering, not thresholds; CHSR-RRF (2026) -
        curriculum-gated retrieval; nDCG and MRR (IR metrics);
        ISO/IEC 42001 (RAG pipeline components documented);
        NIST AI RMF MEASURE 2.5 (schema validation);
        AERA/APA/NCME 2014 Std 13.7 (rerank_score and rank name their
        construct); EU AI Act Art.14 (teacher sees the ranked order at
        G5); Rule 11 (prompt is MASTER_KC_RERANK_PROMPT.md).

        Reads the Claude rerank JSON produced by the teacher using
        MASTER_KC_RERANK_PROMPT.md. Returns survivors in rank order
        with rerank_score and rerank_note attached to each entry.
        """
        if rerank_file is None:
            return survivors
        path = _Path(rerank_file)
        try:
            raw = path.read_text(encoding="utf-8")
        except FileNotFoundError:
            raise CommandError("Rerank file not found: " + str(path))
        try:
            data = extract_json(raw)
        except ValueError as exc:
            raise CommandError("Invalid JSON in rerank file: " + str(exc))

        ranking = data.get("ranking") or []
        if not ranking:
            raise CommandError("Rerank file has no 'ranking' entries.")

        verdicts = {}
        for r in ranking:
            idx = _int_or_none(r.get("index"))
            if idx is None:
                continue
            verdicts[idx] = {
                "rank": _int_or_none(r.get("rank")),
                "rerank_score": _float_or_none(r.get("rerank_score")),
                "rerank_note": _clean(r.get("rerank_note")),
            }

        ranked = []
        for entry in survivors:
            i = entry.get("index")
            v = verdicts.get(i) if i is not None else None
            if v is None or v["rank"] is None:
                self.stderr.write(
                    "WARN survivor index " + str(i)
                    + ": missing rerank entry, ranked last")
                entry["rank"] = 9999
                entry["rerank_score"] = None
                entry["rerank_note"] = ""
            else:
                entry["rank"] = v["rank"]
                entry["rerank_score"] = v["rerank_score"]
                entry["rerank_note"] = v["rerank_note"]
            ranked.append(entry)

        ranked.sort(key=lambda e: e.get("rank", 9999))

        for n, entry in enumerate(ranked, start=1):
            entry["rank"] = n

        self.stdout.write(
            "Reranked: " + str(len(ranked)) + " entry(ies). Top rank: "
            + (ranked[0].get("text", "")[:60] if ranked else "(none)"))
        return ranked

    def _build_ladder(self, ranked, ladder_file):
        """Attach a guided Socratic ladder to each ranked survivor.

        Standards: Polya, How to Solve It (1945) - four-phase scaffold
        (understand, plan, execute, reflect); Kirschner, Sweller &
        Clark (2006), Educational Psychologist 41(2), 75-86 -
        minimally guided instruction is less effective than guided
        instruction for novices; Sweller et al. (2011) Cognitive Load
        Theory - worked-example effect; Rosenshine (2012) - small
        steps, many questions; Hattie & Timperley (2007) - feed-forward
        answers where-to-next; Wood, Bruner & Ross (1976) - scaffolding;
        Vygotsky (1978) - ZPD; AERA/APA/NCME 2014 Std 13.7 - each step
        names its construct (order, polya_phase, question, hint,
        expected_response, worked_example); EU AI Act Art.14 - teacher
        approves at G5; ISO/IEC 42001 Clause 7.5; ISO 9001:2015 7.5.3;
        Rule 11 (prompt is MASTER_KC_SOCRATIC_LADDER_PROMPT.md).

        Reads the ladder JSON produced by the teacher using
        MASTER_KC_SOCRATIC_LADDER_PROMPT.md. Returns a list of ladder
        dicts, one per surviving misconception, in rank order.
        """
        if ladder_file is None:
            return []
        path = _Path(ladder_file)
        try:
            raw = path.read_text(encoding="utf-8")
        except FileNotFoundError:
            raise CommandError("Ladder file not found: " + str(path))
        try:
            data = extract_json(raw)
        except ValueError as exc:
            raise CommandError("Invalid JSON in ladder file: " + str(exc))

        ladders_in = data.get("ladders") or []
        if not ladders_in:
            raise CommandError("Ladder file has no 'ladders' entries.")

        by_index = {}
        for l in ladders_in:
            idx = _int_or_none(l.get("misconception_index"))
            if idx is None:
                continue
            steps_in = l.get("steps") or []
            steps = []
            for s in steps_in:
                steps.append({
                    "order": _int_or_none(s.get("order")),
                    "polya_phase": _clean(s.get("polya_phase")),
                    "question": _clean(s.get("question")),
                    "hint": _clean(s.get("hint")),
                    "expected_response": _clean(s.get("expected_response")),
                    "worked_example": _clean(s.get("worked_example")),
                })
            steps.sort(key=lambda x: x["order"] if x["order"] is not None else 9999)
            for n, s in enumerate(steps, start=1):
                s["order"] = n
            by_index[idx] = steps

        ladder = []
        missing = 0
        for entry in ranked:
            idx = entry.get("index")
            steps = by_index.get(idx, [])
            if not steps:
                self.stderr.write(
                    "WARN survivor index " + str(idx)
                    + ": no ladder provided, skipped")
                missing += 1
                continue
            ladder.append({
                "misconception_index": idx,
                "rank": entry.get("rank"),
                "misconception_text": entry.get("text", ""),
                "steps": steps,
            })

        if not ladder:
            raise CommandError(
                "No ladders attached. Cannot store a KC with zero ladders.")

        self.stdout.write(
            "Ladders attached: " + str(len(ladder))
            + " (missing: " + str(missing) + ")")
        return ladder
