"""AI Expert Panel — governs all student task submissions.

Standards:
- AERA/APA/NCME 2014 (content validity)
- Polit & Beck CVI thresholds (I-CVI >= 0.78, S-CVI/Ave >= 0.90)
- MACS multi-agent consensus (4-of-5 + DRR)
- Dual-LLM verification (independent solver)
- OWASP ASVS 4.3.1 (no unauthenticated admin path)
- ALCOA+ attribution

Rule: No single agent passes a gate. Panel decides collectively.
Rule: Agents are pluggable. LLM-backed upgrade requires no interface change.
"""
from dataclasses import dataclass, field
from typing import Callable
import hashlib


# ---------------------------------------------------------------------------
# Verdict
# ---------------------------------------------------------------------------
@dataclass
class AgentVerdict:
    agent: str
    score: float          # 0.0 - 1.0
    confidence: float     # 0.0 - 1.0
    rationale: str
    flags: list = field(default_factory=list)
    framework_ref: str = ""   # Rule H: every diagnostic claim names its framework


# ---------------------------------------------------------------------------
# LLM interface (stub — plug real client later without changing agents)
# ---------------------------------------------------------------------------
class LLMClient:
    """Default client. Deterministic. No network calls.

    Override by setting panel.llm_client to any object with .ask(prompt).
    """
    def ask(self, prompt: str) -> str:
        return ""


# ---------------------------------------------------------------------------
# Base agent
# ---------------------------------------------------------------------------
class BaseAgent:
    name = "BASE"
    weight = 1.0

    def __init__(self, llm_client=None):
        self.llm = llm_client or LLMClient()

    def evaluate(self, task, payload: dict, context: dict) -> AgentVerdict:
        raise NotImplementedError


# ---------------------------------------------------------------------------
# A1 — Content Expert (rubric check on structure + plausibility)
# ---------------------------------------------------------------------------
class ContentExpert(BaseAgent):
    name = "A1"

    def evaluate(self, task, payload, context):
        flags = []
        kcs = payload.get("kcs") or []
        if not isinstance(kcs, list) or not kcs:
            flags.append("empty_kcs")
        for i, k in enumerate(kcs, 1):
            if not isinstance(k, dict):
                flags.append(f"kcs[{i}]_not_dict"); continue
            for f in ("code", "title", "description"):
                v = k.get(f)
                if not v or not isinstance(v, str) or len(v.strip()) < 3:
                    flags.append(f"kcs[{i}].{f}_invalid")
        score = max(0.0, 1.0 - 0.15 * len(flags))
        conf = 0.9 if not flags else 0.75
        return AgentVerdict(
            agent=self.name, score=score, confidence=conf,
            rationale=f"{len(kcs)} KCs, {len(flags)} flags",
            flags=flags,
        )


# ---------------------------------------------------------------------------
# A1p — Independent Solver (sanity + no-corruption check)
# ---------------------------------------------------------------------------
class IndependentSolver(BaseAgent):
    name = "A1p"

    def evaluate(self, task, payload, context):
        kcs = payload.get("kcs") or []
        flags = []
        # independent structural re-derivation
        codes = [k.get("code") for k in kcs if isinstance(k, dict)]
        if len(codes) != len(set(codes)):
            flags.append("duplicate_codes")
        if any(len(c or "") < 3 for c in codes):
            flags.append("short_codes")
        score = 1.0 if not flags else 0.5
        return AgentVerdict(
            agent=self.name, score=score, confidence=0.85,
            rationale=f"dup={len(codes)-len(set(codes))}",
            flags=flags,
        )


# ---------------------------------------------------------------------------
# A2 — Curriculum Aligner (KC code format matches expected book pattern)
# ---------------------------------------------------------------------------
class CurriculumAligner(BaseAgent):
    name = "A2"

    def evaluate(self, task, payload, context):
        ref = (context.get("book_prefix") or "").strip().upper()
        if ref.endswith("-BOOK"):
            ref = ref[:-5]
        parts = ref.split("-")
        if len(parts) >= 2 and parts[0] and parts[1].isdigit():
            expected_prefix = "C9-" + parts[0]
        else:
            expected_prefix = ref
        flags = []
        kcs = payload.get("kcs") or []
        for i, k in enumerate(kcs, 1):
            code = (k.get("code") or "").upper() if isinstance(k, dict) else ""
            if expected_prefix and not code.startswith(expected_prefix):
                flags.append(f"kcs[{i}].code_not_{expected_prefix}")
        score = 1.0 if not flags else 0.4
        return AgentVerdict(
            agent=self.name, score=score, confidence=0.8,
            rationale=f"prefix={expected_prefix} flags={len(flags)}",
            flags=flags,
        )


# ---------------------------------------------------------------------------
# A3 — Cognitive Classifier (heuristic — length + verb markers)
# ---------------------------------------------------------------------------
class CognitiveClassifier(BaseAgent):
    name = "A3"

    def evaluate(self, task, payload, context):
        kcs = payload.get("kcs") or []
        score = 1.0
        flags = []
        for i, k in enumerate(kcs, 1):
            desc = (k.get("description") or "").lower() if isinstance(k, dict) else ""
            if len(desc) < 20:
                flags.append(f"kcs[{i}].desc_too_short")
        if flags:
            score = 0.5
        return AgentVerdict(
            agent=self.name, score=score, confidence=0.75,
            rationale=f"{len(flags)} short descriptions",
            flags=flags,
        )


# ---------------------------------------------------------------------------
# A5 — Bias Auditor (placeholder; veto power)
# ---------------------------------------------------------------------------
class BiasAuditor(BaseAgent):
    name = "A5"
    veto = True

    def evaluate(self, task, payload, context):
        # deterministic: no-op for now; real bias check plugs in later
        return AgentVerdict(
            agent=self.name, score=1.0, confidence=0.6,
            rationale="no bias markers detected", flags=[],
        )


# ---------------------------------------------------------------------------
# M6a — Misconception Expert (Stage 6) — Rule H compliance
# ---------------------------------------------------------------------------
class MisconceptionExpert(BaseAgent):
    """Stage 6 agent — every misconception names its governing framework.
    Standards: Rule H; AERA/APA/NCME 2014 Std 1.0 + 13.7; MISTAKE."""
    name = "M6a"

    def evaluate(self, task, payload, context):
        misconceptions = payload.get("misconceptions") or []
        flags = []
        if not isinstance(misconceptions, list) or not misconceptions:
            flags.append("empty_misconceptions")
        for i, m in enumerate(misconceptions, 1):
            if not isinstance(m, dict):
                flags.append("m[%d]_not_dict" % i); continue
            fw = (m.get("framework_ref") or "").strip()
            if not fw or len(fw) < 3:
                flags.append("m[%d].framework_ref_missing" % i)
            text = (m.get("text") or "").strip()
            if len(text) < 10:
                flags.append("m[%d].text_too_short" % i)
        score = max(0.0, 1.0 - 0.20 * len(flags))
        conf = 0.9 if not flags else 0.7
        return AgentVerdict(
            agent=self.name, score=score, confidence=conf,
            rationale="%d misconceptions, %d flags" % (len(misconceptions), len(flags)),
            flags=flags,
        )


# ---------------------------------------------------------------------------
# M6b — Mechanism Verifier (Stage 6) — MISTAKE cycle consistency
# ---------------------------------------------------------------------------
class MechanismVerifier(BaseAgent):
    """Stage 6 agent — every misconception carries a coherent faulty-
    reasoning mechanism and a real-world anchor.
    Standards: MISTAKE (Ross & Andreas); Rule H; AERA 2014 Std 13.7."""
    name = "M6b"

    def evaluate(self, task, payload, context):
        misconceptions = payload.get("misconceptions") or []
        flags = []
        if not isinstance(misconceptions, list) or not misconceptions:
            flags.append("empty_misconceptions")
        for i, m in enumerate(misconceptions, 1):
            if not isinstance(m, dict):
                flags.append("m[%d]_not_dict" % i); continue
            mech = (m.get("mechanism") or "").strip()
            if len(mech) < 20:
                flags.append("m[%d].mechanism_too_short" % i)
            anchor = (m.get("real_world_anchor") or "").strip()
            if len(anchor) < 5:
                flags.append("m[%d].anchor_missing" % i)
        score = max(0.0, 1.0 - 0.20 * len(flags))
        conf = 0.85 if not flags else 0.7
        return AgentVerdict(
            agent=self.name, score=score, confidence=conf,
            rationale="%d misconceptions, %d mechanism flags" % (len(misconceptions), len(flags)),
            flags=flags,
        )


# ---------------------------------------------------------------------------
# L7a — Ladder Builder (Stage 7) — Polya phase discipline
# ---------------------------------------------------------------------------
class LadderBuilder(BaseAgent):
    """Stage 7 agent — every ladder step carries a valid Polya phase and a
    real question.
    Standards: Polya 1945; Kirschner-Sweller-Clark 2006; AERA Std 13.7."""
    name = "L7a"
    VALID_PHASES = {"UNDERSTAND", "PLAN", "EXECUTE", "REFLECT"}

    def evaluate(self, task, payload, context):
        ladders = payload.get("ladders") or []
        flags = []
        if not isinstance(ladders, list) or not ladders:
            flags.append("empty_ladders")
        for li, ladder in enumerate(ladders, 1):
            if not isinstance(ladder, dict):
                flags.append("ladder[%d]_not_dict" % li); continue
            steps = ladder.get("steps") or []
            if not isinstance(steps, list) or not steps:
                flags.append("ladder[%d].empty_steps" % li); continue
            for si, step in enumerate(steps, 1):
                if not isinstance(step, dict):
                    flags.append("ladder[%d].step[%d]_not_dict" % (li, si)); continue
                phase = (step.get("polya_phase") or "").strip().upper()
                if phase not in self.VALID_PHASES:
                    flags.append("ladder[%d].step[%d].bad_phase" % (li, si))
                q = (step.get("question") or "").strip()
                if len(q) < 10:
                    flags.append("ladder[%d].step[%d].question_too_short" % (li, si))
        score = max(0.0, 1.0 - 0.15 * len(flags))
        conf = 0.9 if not flags else 0.7
        return AgentVerdict(
            agent=self.name, score=score, confidence=conf,
            rationale="%d ladders, %d phase/question flags" % (len(ladders), len(flags)),
            flags=flags,
        )


# ---------------------------------------------------------------------------
# L7b — Step Sequencer (Stage 7) — 3-6 step ladder, sequential order
# ---------------------------------------------------------------------------
class StepSequencer(BaseAgent):
    """Stage 7 agent — each ladder has 3-6 steps, ordered 1..N with no gaps.
    Standards: Sweller 2011; Rosenshine 2012; Wood-Bruner-Ross 1976."""
    name = "L7b"
    MIN_STEPS = 3
    MAX_STEPS = 6

    def evaluate(self, task, payload, context):
        ladders = payload.get("ladders") or []
        flags = []
        if not isinstance(ladders, list) or not ladders:
            flags.append("empty_ladders")
        for li, ladder in enumerate(ladders, 1):
            if not isinstance(ladder, dict):
                flags.append("ladder[%d]_not_dict" % li); continue
            steps = ladder.get("steps") or []
            if not isinstance(steps, list):
                flags.append("ladder[%d].steps_not_list" % li); continue
            n = len(steps)
            if n < self.MIN_STEPS or n > self.MAX_STEPS:
                flags.append("ladder[%d].step_count=%d" % (li, n))
            orders = [s.get("order") if isinstance(s, dict) else None for s in steps]
            expected = list(range(1, n + 1))
            if orders != expected:
                flags.append("ladder[%d].orders_bad" % li)
        score = max(0.0, 1.0 - 0.20 * len(flags))
        conf = 0.85 if not flags else 0.7
        return AgentVerdict(
            agent=self.name, score=score, confidence=conf,
            rationale="%d ladders, %d sequencing flags" % (len(ladders), len(flags)),
            flags=flags,
        )


# ---------------------------------------------------------------------------
# S11a — Story Structure Checker (Stage 11) — named character + events
# ---------------------------------------------------------------------------
class StoryStructureChecker(BaseAgent):
    """Stage 11 agent — story_text 250-400 words, named character, >=3 events.
    Standards: Tobler et al. 2025 (ETH Zurich); SILC; Rule H; AERA Std 13.7."""
    name = "S11a"
    MIN_WORDS = 250
    MAX_WORDS = 400
    MIN_EVENTS = 3

    EVENT_MARKERS = (
        "phir", "aur phir", "uske baad", "us ke baad", "iske baad",
        "is ke baad", "baad mein", "baad me", "aakhir", "aakhir mein",
        "agli", "agle", "agla", "doosre din", "doosray din", "doosri din",
        "jab", "jab ke", "ek din", "aik din", "subah", "dopehar", "shaam",
        "raat", "raat ko", "din mein",
    )

    def _iter_stories(self, payload):
        subjects = payload.get("subjects") or []
        if not isinstance(subjects, list):
            return
        for sub in subjects:
            if not isinstance(sub, dict):
                continue
            for s in sub.get("stories") or []:
                if isinstance(s, dict):
                    yield s

    def evaluate(self, task, payload, context):
        import re
        flags = []
        stories = list(self._iter_stories(payload))
        if not stories:
            flags.append("empty_stories")
        for i, s in enumerate(stories, 1):
            text = (s.get("story_text") or "").strip()
            if not text:
                flags.append("story[%d].empty" % i); continue
            wc = len(text.split())
            if wc < self.MIN_WORDS:
                flags.append("story[%d].too_short=%d" % (i, wc))
            if wc > self.MAX_WORDS:
                flags.append("story[%d].too_long=%d" % (i, wc))
            if not re.search(r"\b[A-Z][a-z]{2,}\b", text):
                flags.append("story[%d].no_named_character" % i)
            low = text.lower()
            events = sum(1 for m in self.EVENT_MARKERS if m in low)
            if events < self.MIN_EVENTS:
                flags.append("story[%d].events=%d" % (i, events))
        score = max(0.0, 1.0 - 0.15 * len(flags))
        conf = 0.85 if not flags else 0.7
        return AgentVerdict(
            agent=self.name, score=score, confidence=conf,
            rationale="%d stories, %d structure flags" % (len(stories), len(flags)),
            flags=flags,
        )


# ---------------------------------------------------------------------------
# S11b — Analogy Verifier (Stage 11) — analogy + bridge phrase + comprehension
# ---------------------------------------------------------------------------
class AnalogyVerifier(BaseAgent):
    """Stage 11 agent — analogy_used present, bridge phrase in story_text,
    comprehension_question present.
    Standards: SILC; Gentner 1983 (analogical reasoning); Rule H; AERA Std 13.7."""
    name = "S11b"
    BRIDGE_MARKERS = (
        "jaise insaan", "insaani duniya", "jaise log", "jaise hum",
        "insaanon mein", "logon mein",
    )
    MIN_ANALOGY = 10
    MIN_COMP = 10

    def _iter_stories(self, payload):
        subjects = payload.get("subjects") or []
        if not isinstance(subjects, list):
            return
        for sub in subjects:
            if not isinstance(sub, dict):
                continue
            for s in sub.get("stories") or []:
                if isinstance(s, dict):
                    yield s

    def evaluate(self, task, payload, context):
        flags = []
        stories = list(self._iter_stories(payload))
        if not stories:
            flags.append("empty_stories")
        for i, s in enumerate(stories, 1):
            analogy = (s.get("analogy_used") or "").strip()
            if len(analogy) < self.MIN_ANALOGY:
                flags.append("story[%d].analogy_too_short" % i)
            text = (s.get("story_text") or "").strip()
            low = text.lower()
            if not any(m in low for m in self.BRIDGE_MARKERS):
                flags.append("story[%d].no_bridge" % i)
            comp = (s.get("comprehension_question") or "").strip()
            if len(comp) < self.MIN_COMP:
                flags.append("story[%d].comp_too_short" % i)
        score = max(0.0, 1.0 - 0.15 * len(flags))
        conf = 0.85 if not flags else 0.7
        return AgentVerdict(
            agent=self.name, score=score, confidence=conf,
            rationale="%d stories, %d analogy flags" % (len(stories), len(flags)),
            flags=flags,
        )


# ---------------------------------------------------------------------------
# D1 — Error Classifier (Panel B, Diagnostic) — Newman Error Analysis
# ---------------------------------------------------------------------------
class ErrorClassifier(BaseAgent):
    """D1 — classifies each wrong answer against Newman's five sequential
    stages: Reading, Comprehension, Transformation, Process, Encoding.

    Deterministic v1.0. LLM upgrade path unchanged (self.llm.ask).
    Standards: Newman 1977 (NSW Dept of Ed.); Rule H (framework
    citation before diagnostic claim); AERA/APA/NCME 2014 Std 1.0 + 13.7.
    """
    name = "D1"
    framework_ref = "Newman 1977"

    # Newman's five stages, with common synonyms the prompt may emit.
    NEWMAN_STAGES = (
        ("READING",        ("READING", "DECODE", "WORD_PROBLEM_READ", "MISREAD_WORD")),
        ("COMPREHENSION",  ("COMPREHENSION", "MEANING", "MISUNDERSTOOD_QUESTION")),
        ("TRANSFORMATION", ("TRANSFORMATION", "SETUP", "SET_UP", "MODEL")),
        ("PROCESS",        ("PROCESS", "PROCESS_SKILLS", "CALCULATION", "ARITHMETIC", "COMPUTE")),
        ("ENCODING",       ("ENCODING", "NOTATION", "WRITE_ANSWER", "FINAL_ANSWER")),
    )

    def _classify(self, error_type):
        et = (error_type or "").upper()
        for stage, keys in self.NEWMAN_STAGES:
            if any(k in et for k in keys):
                return stage
        return None

    def evaluate(self, task, payload, context):
        questions = payload.get("questions") or []
        flags = []
        classified = []
        math_count = 0

        if not questions:
            flags.append("no_questions")

        for i, q in enumerate(questions, 1):
            if not isinstance(q, dict):
                flags.append("q[%d]_not_dict" % i); continue
            fw = (q.get("framework_cited") or "").strip()
            if fw == "Newman":
                math_count += 1
                wvc = q.get("wrong_vs_correct") or []
                if not wvc:
                    flags.append("q[%d].empty_wvc" % i)
                for j, w in enumerate(wvc, 1):
                    if not isinstance(w, dict):
                        flags.append("q[%d].wvc[%d]_not_dict" % (i, j)); continue
                    stage = self._classify(w.get("error_type"))
                    if stage:
                        classified.append({"q": i, "wvc": j, "stage": stage})
                    else:
                        flags.append("q[%d].wvc[%d].no_newman_stage" % (i, j))

        # Rule H: if Newman applies to no question, cap confidence.
        if math_count == 0:
            score = 1.0
            conf = 0.5
            rationale = "no Newman-applicable questions (framework_cited != Newman)"
        else:
            score = max(0.0, 1.0 - 0.15 * len(flags))
            conf = 0.85 if not flags else 0.65
            rationale = "%d math q, %d classified, %d flags" % (
                math_count, len(classified), len(flags))

        return AgentVerdict(
            agent=self.name, score=score, confidence=conf,
            rationale=rationale, flags=flags,
            framework_ref=self.framework_ref,
        )


# ---------------------------------------------------------------------------
# D2 — Depth Reader (Panel B, Diagnostic) — SOLO Taxonomy
# ---------------------------------------------------------------------------
class DepthReader(BaseAgent):
    """D2 — assigns a SOLO level 0-4 to each question's understanding.

    Levels: 0 Prestructural / 1 Unistructural / 2 Multistructural /
    3 Relational / 4 Extended Abstract.

    Deterministic v1.0: reads explicit solo_level if present; else
    derives from band + logical_analysis length. LLM upgrade path
    unchanged (self.llm.ask).

    Standards: Biggs & Collis 1989 (SOLO); Rule H (framework citation);
    AERA/APA/NCME 2014 Std 1.0 + 13.7.
    """
    name = "D2"
    framework_ref = "Biggs & Collis 1989 (SOLO)"

    # Band -> base SOLO level (deterministic fallback).
    BAND_TO_SOLO = {
        "EXCELLENT": 3, "GOOD": 3,
        "FAIR": 2,
        "BELOW AVERAGE": 1,
        "POOR": 0, "WRONG": 0, "NOT ATTEMPTED": 0,
    }

    def _from_band(self, band):
        b = (band or "").strip().upper()
        return self.BAND_TO_SOLO.get(b)

    def evaluate(self, task, payload, context):
        questions = payload.get("questions") or []
        flags = []
        levels = []
        solo_count = 0

        if not questions:
            flags.append("no_questions")

        for i, q in enumerate(questions, 1):
            if not isinstance(q, dict):
                flags.append("q[%d]_not_dict" % i); continue
            fw = (q.get("framework_cited") or "").strip()
            if fw != "SOLO":
                continue
            solo_count += 1

            explicit = q.get("solo_level")
            if isinstance(explicit, int) and 0 <= explicit <= 4:
                levels.append(explicit)
                continue

            derived = self._from_band(q.get("band"))
            if derived is None:
                flags.append("q[%d].no_solo_level" % i)
                continue
            # Extended Abstract (4) requires an explicit signal.
            if derived == 3 and "generaliz" in (q.get("logical_analysis") or "").lower():
                derived = 4
            levels.append(derived)

        if solo_count == 0:
            score = 1.0
            conf = 0.5
            rationale = "no SOLO-applicable questions (framework_cited != SOLO)"
        else:
            score = max(0.0, 1.0 - 0.15 * len(flags))
            conf = 0.85 if not flags else 0.65
            rationale = "%d SOLO q, %d leveled, %d flags" % (
                solo_count, len(levels), len(flags))

        return AgentVerdict(
            agent=self.name, score=score, confidence=conf,
            rationale=rationale, flags=flags,
            framework_ref=self.framework_ref,
        )


# ---------------------------------------------------------------------------
# D3 — Feedback Writer (Panel B, Diagnostic) — Hattie & Timperley 2007
# ---------------------------------------------------------------------------
class FeedbackWriter(BaseAgent):
    """D3 — verifies that the feedback answers the three questions:
    Where am I going? (Feed Up) / How am I going? (Feed Back) /
    Where to next? (Feed Forward).

    Rule G: all student/parent-facing text must be Roman Urdu, Latin-1
    range (no codepoints > U+00FF).

    Veto: any punishment or abusive language fails the panel.
    Praise-only (no next step) is flagged, not vetoed (Hattie 2007:
    praise has near-zero effect; feedback with a next step does not).

    Standards: Hattie & Timperley 2007; Rule G (language);
    AERA/APA/NCME 2014 Std 1.0 + 13.7.
    """
    name = "D3"
    framework_ref = "Hattie & Timperley 2007"
    veto = True

    PUNISHMENT = (
        "lazy", "stupid", "useless", "worthless", "shameless",
        "hopeless", "good-for-nothing", "idiot", "dumb", "fool",
        "nalaiq", "bewaqoof", "nikamma",
    )

    def _latin1_safe(self, text):
        if not text:
            return True
        return all(ord(ch) <= 0x00FF for ch in text)

    def _contains(self, text, words):
        low = (text or "").lower()
        return [w for w in words if w in low]

    def evaluate(self, task, payload, context):
        questions = payload.get("questions") or []
        overall = (payload.get("overall_feedback") or "").strip()
        parent = (context.get("parent_summary") or {}) if isinstance(context, dict) else {}

        flags = []
        veto_flags = []

        # Feed Up — student-level
        feed_up_student = bool(overall)
        if not feed_up_student:
            flags.append("no_overall_feedback")
        day_overview = (parent.get("day_overview") or "").strip()
        feed_up_parent = bool(day_overview)

        # Feed Back + Feed Forward — per question
        q_missing_back = 0
        q_missing_fwd = 0
        for i, q in enumerate(questions, 1):
            if not isinstance(q, dict):
                continue
            ec = q.get("expert_comment") or {}
            if not isinstance(ec, dict):
                ec = {}
            if not (ec.get("strength") or "").strip() or not (ec.get("need") or "").strip():
                q_missing_back += 1
                flags.append("q[%d].missing_feed_back" % i)
            if not (ec.get("suggestion") or "").strip():
                q_missing_fwd += 1
                flags.append("q[%d].missing_feed_forward" % i)

        # Rule G: scan every student-facing string
        texts = [overall, day_overview]
        texts += [str(x) for x in (parent.get("strengths") or [])]
        texts += [str(x) for x in (parent.get("needs") or [])]
        texts += [str(x) for x in (parent.get("actions") or [])]
        for q in questions:
            if not isinstance(q, dict):
                continue
            ec = q.get("expert_comment") or {}
            if isinstance(ec, dict):
                texts += [str(ec.get("strength") or ""),
                          str(ec.get("need") or ""),
                          str(ec.get("suggestion") or "")]
        # Rule G violation -> veto. Latin-1 PDFs physically cannot render
        # codepoints > U+00FF, so this is a rendering constraint, not a
        # style preference. Standards: Rule G; WCAG 3.1.1/3.1.2;
        # BCP 47 / ISO 15924; ISO/IEC 20016-1:2014.
        non_latin = [t for t in texts if t and not self._latin1_safe(t)]
        if non_latin:
            veto_flags.append("rule_g_non_latin1_count=%d" % len(non_latin))

        # Veto: punishment language anywhere
        for t in texts:
            hits = self._contains(t, self.PUNISHMENT)
            if hits:
                veto_flags.append("punishment:%s" % ",".join(hits))

        # Score. Feed Forward (Hattie 2007: "where to next") is the
        # highest-value category, so its absence weighs equal to Feed Back.
        if not questions and not overall:
            score = 1.0
            conf = 0.5
            rationale = "no feedback content to evaluate"
        else:
            denom = max(1, 1 + len(questions))
            earned_back = (len(questions) - q_missing_back)
            earned_fwd = (len(questions) - q_missing_fwd)
            earned = ((1 if feed_up_student else 0)
                      + 0.5 * earned_back
                      + 0.5 * earned_fwd)
            score = max(0.0, float(earned) / float(denom))
            if feed_up_parent and score < 1.0:
                score = min(1.0, score + 0.05)
            conf = 0.85 if not flags else 0.65
            rationale = ("feed_up=%s parent_up=%s back_missing=%d fwd_missing=%d flags=%d"
                         % (feed_up_student, feed_up_parent, q_missing_back,
                            q_missing_fwd, len(flags)))

        # Veto: punishment language forces the score to zero so D3 cannot
        # count toward consensus on a paper it is vetoing (Hattie 2007:
        # punishment has negative effect size; paper must route to teacher).
        if veto_flags:
            score = 0.0

        return AgentVerdict(
            agent=self.name, score=score, confidence=conf,
            rationale=rationale, flags=flags + veto_flags,
            framework_ref=self.framework_ref,
        )


# ---------------------------------------------------------------------------
# D4 — Mastery Path Builder (Panel B, Diagnostic) — Bloom + DBI/MTSS
# ---------------------------------------------------------------------------
class MasteryPathBuilder(BaseAgent):
    """D4 — verifies the corrective task set that closes the gap.

    Bloom 1968: correctives must be specific to the diagnosed error,
    not generic advice. Keller 1968 PSI: the mastery unit is four
    corrective tasks. DBI/MTSS: each task maps to a diagnosed
    misconception.

    Checks:
      - exactly 4 tasks (Keller PSI unit)
      - each task has a non-empty title (>= 10 chars)
      - each task has a non-empty model_answer (Bloom: correctives
        must be specific)
      - each category in the allowed set (or empty; empty flagged)

    Standards: Bloom 1968; Keller 1968 (PSI); DBI/MTSS (NCII);
    AERA/APA/NCME 2014 Std 1.0 + 13.7.
    """
    name = "D4"
    framework_ref = "Bloom 1968 + DBI/MTSS"
    REQUIRED_TASKS = 4
    MIN_TITLE = 10
    ALLOWED_CATEGORIES = {"STORY", "PRACTICE", "READING", "WRITING",
                          "REVISION", "EXERCISE", "PROBLEM"}

    def evaluate(self, task, payload, context):
        tasks = payload.get("next_day_tasks") or []
        flags = []
        if not isinstance(tasks, list):
            tasks = []

        n = len(tasks)
        if n != self.REQUIRED_TASKS:
            flags.append("task_count=%d_expected_%d" % (n, self.REQUIRED_TASKS))

        for i, t in enumerate(tasks, 1):
            if not isinstance(t, dict):
                flags.append("task[%d]_not_dict" % i); continue
            title = (t.get("title") or "").strip()
            if len(title) < self.MIN_TITLE:
                flags.append("task[%d].title_too_short" % i)
            ma = (t.get("model_answer") or "").strip()
            if not ma:
                flags.append("task[%d].missing_model_answer" % i)
            cat = (t.get("category") or "").strip().upper()
            if not cat:
                flags.append("task[%d].missing_category" % i)
            elif cat not in self.ALLOWED_CATEGORIES:
                flags.append("task[%d].unknown_category=%s" % (i, cat))

        if not tasks:
            score = 1.0
            conf = 0.5
            rationale = "no next_day_tasks to evaluate"
        else:
            score = max(0.0, 1.0 - 0.12 * len(flags))
            conf = 0.85 if not flags else 0.7
            rationale = "%d tasks, %d flags" % (n, len(flags))

        return AgentVerdict(
            agent=self.name, score=score, confidence=conf,
            rationale=rationale, flags=flags,
            framework_ref=self.framework_ref,
        )


# ---------------------------------------------------------------------------
# Panel = agents + arbiter
# ---------------------------------------------------------------------------
AGENTS = [
    ContentExpert(), IndependentSolver(), CurriculumAligner(),
    CognitiveClassifier(), BiasAuditor(),
]

# Panel B — Diagnostic (paper grading). D2-D4 arrive in P7-3, P7-4, P7-5.
# Design: design/DIAGNOSTIC-PANEL-v1.0.md §3.
DIAGNOSTIC_AGENTS = (
    ErrorClassifier(),
    DepthReader(),
    FeedbackWriter(),
    MasteryPathBuilder(),
)
MIN_SCORE_PER_AGENT = 0.70
CONSENSUS = 4          # 4 of 5
DRR_MIN = 0.60

# ---------------------------------------------------------------------------
# Turn 19 (2026-10-11) — STAGE-AWARE ROUTING
# Per-stage agent tuples and thresholds. Default = current 5-agent panel
# so all existing callers keep their exact behaviour.
# Standards: Cooper Stage-Gate; ADDIE (Evaluate); IEEE 1012-2016 (V&V per
#   life-cycle stage); ISO/IEC/IEEE 29119-3 5.4 (test basis per stage);
#   AERA/APA/NCME 2014 Std 1.0; Rule 13 (oversight mode per task);
#   design/EXPERT-PANEL-v2.0.md.
# ---------------------------------------------------------------------------
DEFAULT_STAGE = 3

STAGE_AGENTS = {
    1:  tuple(AGENTS),
    3:  tuple(AGENTS),
    5:  tuple(AGENTS),
    6:  (MisconceptionExpert(), MechanismVerifier(), BiasAuditor()),
    7:  (LadderBuilder(), StepSequencer(), BiasAuditor()),
    10: tuple(AGENTS),
    11: (StoryStructureChecker(), AnalogyVerifier(), BiasAuditor()),
}

STAGE_RULES = {
    1:  {"min_score": MIN_SCORE_PER_AGENT, "consensus": CONSENSUS, "drr_min": DRR_MIN},
    3:  {"min_score": MIN_SCORE_PER_AGENT, "consensus": CONSENSUS, "drr_min": DRR_MIN},
    5:  {"min_score": MIN_SCORE_PER_AGENT, "consensus": CONSENSUS, "drr_min": DRR_MIN},
    6:  {"min_score": MIN_SCORE_PER_AGENT, "consensus": 2, "drr_min": DRR_MIN, "veto_agents": ["A5"]},
    7:  {"min_score": MIN_SCORE_PER_AGENT, "consensus": 2, "drr_min": DRR_MIN, "veto_agents": ["A5"]},
    10: {"min_score": MIN_SCORE_PER_AGENT, "consensus": CONSENSUS, "drr_min": DRR_MIN},
    11: {"min_score": MIN_SCORE_PER_AGENT, "consensus": 2, "drr_min": DRR_MIN, "veto_agents": ["A5"]},
}


@dataclass
class PanelDecision:
    passed: bool
    consensus_count: int
    drr: float
    stage: int = DEFAULT_STAGE
    verdicts: list = field(default_factory=list)
    blockers: list = field(default_factory=list)
    action_text: str = ""

    def as_dict(self):
        return {
            "passed": self.passed,
            "stage": self.stage,
            "consensus_count": self.consensus_count,
            "drr": round(self.drr, 3),
            "blockers": self.blockers,
            "action_text": self.action_text,
            "agents": [{"agent": v.agent, "score": v.score,
                        "confidence": v.confidence, "flags": v.flags}
                       for v in self.verdicts],
        }


def _drr(scores):
    if not scores or max(scores) == 0:
        return 0.0
    return min(scores) / max(scores)


def evaluate_panel(task, payload: dict, context: dict | None = None,
                   stage: int | None = None) -> PanelDecision:
    """Evaluate a submission.

    stage=None (default) preserves prior behaviour exactly (stage 3).
    stage=N selects STAGE_AGENTS[N] and STAGE_RULES[N].
    Unknown stage falls back to DEFAULT_STAGE.
    """
    context = context or {}
    stage = DEFAULT_STAGE if stage is None else int(stage)
    agents = STAGE_AGENTS.get(stage)
    rules = STAGE_RULES.get(stage)
    if agents is None or rules is None:
        context = dict(context)
        context["_stage_unregistered"] = stage
        stage = DEFAULT_STAGE
        agents = STAGE_AGENTS[stage]
        rules = STAGE_RULES[stage]

    min_score = rules["min_score"]
    consensus_required = rules["consensus"]
    drr_min = rules["drr_min"]

    verdicts = [a.evaluate(task, payload, context) for a in agents]
    veto_names = set(rules.get("veto_agents", []))
    scoring_verdicts = [v for v in verdicts if v.agent not in veto_names]
    accepted = [v for v in scoring_verdicts if v.score >= min_score]
    consensus = len(accepted)

    scores = [v.score for v in verdicts]
    drr = _drr(scores)

    blockers = []
    if consensus < consensus_required:
        blockers.append(f"consensus={consensus}/{consensus_required}")
    if drr < drr_min:
        blockers.append(f"drr={drr:.2f}<{drr_min}")

    for v in verdicts:
        agent = next((a for a in agents if a.name == v.agent), None)
        if getattr(agent, "veto", False) and v.flags:
            blockers.append(f"veto_{v.agent}: {v.flags}")

    passed = not blockers
    if passed:
        action = "Accepted. Shabash!"
    else:
        action = "Please dobara koshish karein: " + "; ".join(blockers[:2])

    return PanelDecision(
        passed=passed, consensus_count=consensus, drr=drr, stage=stage,
        verdicts=verdicts, blockers=blockers, action_text=action,
    )


# ---------------------------------------------------------------------------
# P13-5 -- CorrectionVerifier
# Verifies that a proposed correction resolves the specific DataQualityIssue.
# Standards: ISO 8000-8 5.2-5.5; TraceGuard-ETL IV (verify-before-accept);
#            Rule 9 (append-only); Rule H (framework_ref required).
# ---------------------------------------------------------------------------
class CorrectionVerifier(BaseAgent):
    name = "CV1"

    def evaluate(self, task, payload, context):
        from exams.models import DataQualityIssue
        flags = []
        iid = payload.get("issue_id") or context.get("issue_id")
        if not iid:
            flags.append("no_issue_id")
        issue = DataQualityIssue.objects.filter(pk=iid).first() if iid else None
        if not issue:
            flags.append("issue_not_found")

        field = (payload.get("field") or "").strip()
        cur = (payload.get("current_value") or "").strip()
        new = (payload.get("corrected_value") or "").strip()
        conf = payload.get("confidence")
        fref = (payload.get("framework_ref") or "").strip()
        rationale = (payload.get("rationale") or "").strip()

        if not field:
            flags.append("field_blank")
        if not new:
            flags.append("corrected_value_blank")
        if new and cur and new == cur:
            flags.append("no_change")
        if not fref:
            flags.append("framework_ref_missing")   # Rule H
        if not rationale:
            flags.append("rationale_blank")
        try:
            conf = float(conf)
        except (TypeError, ValueError):
            conf = 0.0
        if conf < 0.7:
            flags.append("low_confidence")

        if issue:
            expected_class = issue.defect_class
            if expected_class in ("MISSING", "WRONG", "MALFORMED") and not new:
                flags.append(f"unresolved_{expected_class}")
            if expected_class == "DUPLICATE" and not payload.get("duplicate_of_id"):
                flags.append("duplicate_needs_sibling_id")
            if expected_class == "INCONSISTENT" and not payload.get("chosen_canonical"):
                flags.append("inconsistent_needs_canonical_choice")
            if expected_class == "ORPHAN" and not new:
                flags.append("orphan_unresolved")

        HARD = {"no_issue_id", "issue_not_found", "field_blank",
                "corrected_value_blank", "no_change",
                "framework_ref_missing", "low_confidence"}
        hard_hit = any(
            f in HARD or f.startswith("unresolved_") or f.startswith("orphan_")
            for f in flags
        )
        score = 0.0 if hard_hit else max(0.0, 1.0 - 0.12 * len(flags))
        conf_out = 0.9 if not flags else 0.7
        return AgentVerdict(
            agent=self.name,
            score=score,
            confidence=conf_out,
            rationale=f"issue={iid} field={field or '?'} flags={len(flags)}",
            flags=flags,
            framework_ref=fref,
        )


# P13-5: register DATA_CORRECTION as stage 20 (post-class definition).
STAGE_AGENTS[20] = (CorrectionVerifier(),)
STAGE_RULES[20] = {
    "min_score": MIN_SCORE_PER_AGENT,
    "consensus": 1,
    "drr_min": 0.0,
}
