"""Mizan — Compliance Score & Anti-Deadlock engine (ALG-007, Phase 7.5).

Standards:
  IEEE 7009-2024 (fail-safe autonomy; defined states)
  Parasuraman, Sheridan & Wickens 2000 (levels of automation)
  DO-178C / IEC 61508 (coverage-metric thresholds)
  NIST AI RMF MEASURE 2.5 / 2.6 (measured validity)
  Nygard 2018 (half-open circuit breaker)
  Saltzer & Schroeder 1975 (fail-safe defaults)
  EU AI Act Art. 14 (meaningful oversight)
  ISO/IEC 42001 §7.5 (documented AI decisions)
  Sheridan-Verplank 1978 (10-level automation ladder)
  Rule 12 (Mizan gates); Rule 13 (HITL); Rule H.

This module NEVER returns "cannot decide".
"""
from dataclasses import dataclass, field, asdict
from typing import Optional


# Weights per ALG-007 §3. Sum = 1.00.
WEIGHTS = {
    "C1": 0.25,   # framework cited (Rule H)
    "C2": 0.20,   # output schema valid
    "C3": 0.15,   # evidence chain complete
    "C4": 0.05,   # cross-model check (optional)
    "C5": 0.10,   # human override path exists
    "C6": 0.15,   # audit trail writeable
    "C7": 0.10,   # no forbidden claim
}

# Diagnostic task types — Rule H forbids any diagnostic claim without a
# cited framework (C1). Amended per DEF-013 (2026-10-08).
DIAGNOSTIC_TYPES = {
    "KC_MISCONCEPTION", "KC_SOCRATIC_LADDER", "KC_TAG",
    "KC_DISCOVERY", "GRADING", "MASTER_GRADING", "STORY",
}

BAND_AUTO_APPROVE             = "AUTO_APPROVE"
BAND_AUTO_APPROVE_WITH_NOTE   = "AUTO_APPROVE_WITH_NOTE"
BAND_HITL                     = "HITL"
BAND_REFUSE_WITH_ROUTE        = "REFUSE_WITH_ROUTE"

ACTION_TEXT = {
    BAND_AUTO_APPROVE:            "Ho gaya",
    BAND_AUTO_APPROVE_WITH_NOTE:  "Ho gaya. Teacher check karenge.",
    BAND_HITL:                    "Aap ka kaam teacher ke paas gaya hai.",
    BAND_REFUSE_WITH_ROUTE:       "Please poora karein.",
}


@dataclass
class Decision:
    cs: float
    band: str
    action_text: str
    provisional: bool
    failed_criteria: list = field(default_factory=list)
    per_ci: dict = field(default_factory=dict)
    teacher_question: str = ""
    task_type: str = ""

    def as_dict(self):
        return asdict(self)


def _band(cs: float, task_type: str = "",
          per_ci: dict = None) -> str:
    """Return the band, honouring hard-stop criteria (ALG-007 §4.1).

    Hard stops force REFUSE regardless of CS:
      - C2 = 0 (any task type): writer cannot run on invalid schema
      - C7 = 0 (any task type): forbidden claim
      - C1 = 0 (diagnostic task types only): Rule H violation
    """
    per_ci = per_ci or {}
    if per_ci.get("C2") == 0 or per_ci.get("C7") == 0:
        return BAND_REFUSE_WITH_ROUTE
    if task_type in DIAGNOSTIC_TYPES and per_ci.get("C1") == 0:
        return BAND_REFUSE_WITH_ROUTE
    if cs >= 0.90:
        return BAND_AUTO_APPROVE
    if cs >= 0.75:
        return BAND_AUTO_APPROVE_WITH_NOTE
    if cs >= 0.50:
        return BAND_HITL
    return BAND_REFUSE_WITH_ROUTE


def compute_cs(per_ci: dict) -> float:
    """Return CS in [0.00, 1.00]."""
    total = 0.0
    for k, w in WEIGHTS.items():
        if per_ci.get(k) == 1:
            total += w
    return round(total, 4)


def _evaluate_ci(task_type: str, ai_output: dict, context: dict) -> dict:
    """Return {C1..C7: 0|1} based on the AI output + context.

    Every criterion is checkable. Defaults are fail-safe (0) except
    C5 and C6 (path existence) which the caller asserts.
    """
    per_ci = {
        "C1": 0, "C2": 0, "C3": 0, "C4": 0,
        "C5": int(context.get("has_override_path", 1)),
        "C6": int(context.get("audit_writeable", 1)),
        "C7": 1,  # assumes safe unless forbidden-claim check fails
    }

    # C1 — framework cited (Rule H). Depends on task type.
    # KC_DISCOVERY and KC_TAG: the framework is embedded in the prompt
    # that produced the output (MASTER_KC_DISCOVERY_PROMPT.md cites
    # Tatsuoka 1983, Templin & Hoffman 2013, de la Torre & Chiu 2016,
    # AERA Std 1.0/13.7). The payload inherits the framework.
    PROMPT_EMBEDDED_FRAMEWORK = {"KC_DISCOVERY", "KC_TAG"}
    if task_type in PROMPT_EMBEDDED_FRAMEWORK:
        per_ci["C1"] = 1
    elif task_type in ("KC_MISCONCEPTION", "KC_SOCRATIC_LADDER",
                       "GRADING", "MASTER_GRADING", "STORY"):
        # Try top-level field first
        fw = (ai_output.get("framework_cited")
              or ai_output.get("framework")
              or "")
        if isinstance(fw, str) and len(fw) >= 3:
            per_ci["C1"] = 1
        elif task_type == "KC_SOCRATIC_LADDER":
            # Stage 5 inherits frameworks cited at stage 4. The
            # payload carries the framework evidence as polya_phase
            # on each step (Polya 1945). Accept that shape.
            # Same class as DEF-024 (framework inside the payload).
            # Standards: Rule 12 (Mizan); Rule 26; 9-stage decision doc.
            VALID_PHASES = {"UNDERSTAND", "PLAN", "EXECUTE", "REFLECT"}
            ladders = ai_output.get("ladders") or []
            if isinstance(ladders, list) and ladders:
                all_ok = True
                for lad in ladders:
                    if not isinstance(lad, dict):
                        all_ok = False; break
                    steps = lad.get("steps") or []
                    if not isinstance(steps, list) or not steps:
                        all_ok = False; break
                    for s in steps:
                        if not isinstance(s, dict):
                            all_ok = False; break
                        phase = (s.get("polya_phase") or "").upper()
                        if phase not in VALID_PHASES:
                            all_ok = False; break
                    if not all_ok:
                        break
                if all_ok:
                    per_ci["C1"] = 1
        else:
            # KC_MISCONCEPTION prompt places framework_ref INSIDE each
            # candidate. Accept that shape (DEF-024 fix).
            cands = ai_output.get("candidates") or []
            if isinstance(cands, list) and cands:
                all_ok = True
                for c in cands:
                    if not isinstance(c, dict):
                        all_ok = False; break
                    fr = (c.get("framework_ref") or "").strip()
                    if len(fr) < 3:
                        all_ok = False; break
                if all_ok:
                    per_ci["C1"] = 1
    else:
        per_ci["C1"] = 1

    # C2 — schema valid (a minimal required-key check per task type).
    if task_type == "BOOK_INGEST":
        # Modern book prompt: {code, title, sections:[...]}
        # Legacy book prompt: {code, title, questions:[...]}
        # Accept either (DEF-024 fix; RFC 761 robustness).
        has_q = isinstance(ai_output.get("questions"), list) and len(ai_output["questions"]) > 0
        has_s = isinstance(ai_output.get("sections"), list) and len(ai_output["sections"]) > 0
        per_ci["C2"] = 1 if (has_q or has_s) else 0
    else:
        required = {
            "KC_MISCONCEPTION":   [("candidates", list)],
            "KC_SOCRATIC_LADDER": [("ladders", list)],
            "KC_TAG":             [("tags", list)],
            "KC_DISCOVERY":       [("kcs", list)],
            "GLOSSARY":           [("entries", list)],
            "STORY":              [("story_text", str)],
        }.get(task_type, [])
        ok = True
        for key, typ in required:
            if key not in ai_output or not isinstance(ai_output.get(key), typ):
                ok = False
                break
        per_ci["C2"] = int(ok)

    # C3 — evidence chain (source_ref/hash present for each item).
    if task_type == "BOOK_INGEST":
        # Sections shape: each section has ref (which IS the source).
        sections = ai_output.get("sections")
        if isinstance(sections, list) and sections:
            if all(isinstance(s, dict) and (s.get("ref") or "").strip()
                   for s in sections):
                per_ci["C3"] = 1
        # Questions shape (legacy): each q has source_ref
        elif isinstance(ai_output.get("questions"), list) and ai_output["questions"]:
            items = ai_output["questions"]
            per_ci["C3"] = int(all(
                (it.get("source_ref") or it.get("source"))
                for it in items if isinstance(it, dict)))
    else:
        items_key = {
            "KC_MISCONCEPTION": "candidates",
            "KC_TAG": "tags",
            "KC_DISCOVERY": "kcs",
            "GLOSSARY": "entries",
        }.get(task_type)
        if items_key and isinstance(ai_output.get(items_key), list):
            items = ai_output[items_key]
            # For candidates: at least require non-empty list
            per_ci["C3"] = 1 if items else 0
        else:
            per_ci["C3"] = 1 if not items_key else 0

    # C4 — cross-model check (optional, currently off by default)
    if context.get("cross_model_checked"):
        per_ci["C4"] = 1

    # C7 — forbidden-claim check.
    forbidden = context.get("forbidden_terms") or []
    text = str(ai_output).lower()
    if any(term.lower() in text for term in forbidden):
        per_ci["C7"] = 0

    return per_ci


def _teacher_question(band: str, failed: list) -> str:
    if band == BAND_AUTO_APPROVE_WITH_NOTE:
        return "Review within 24h: " + (", ".join(failed) or "none")
    if band == BAND_HITL:
        return "Approve today: " + (", ".join(failed) or "none")
    if band == BAND_REFUSE_WITH_ROUTE:
        return ("Provisional — accept/edit/reject? Failed: "
                + (", ".join(failed) or "none"))
    return ""


def decide(task_type: str, ai_output: dict,
           context: Optional[dict] = None) -> Decision:
    """Return a Decision. NEVER returns 'cannot decide'."""
    ctx = dict(context or {})
    per_ci = _evaluate_ci(task_type, ai_output or {}, ctx)
    cs = compute_cs(per_ci)
    band = _band(cs, task_type=task_type, per_ci=per_ci)
    failed = [k for k, v in per_ci.items() if v == 0]
    provisional = (band == BAND_REFUSE_WITH_ROUTE)

    return Decision(
        cs=cs,
        band=band,
        action_text=ACTION_TEXT[band],
        provisional=provisional,
        failed_criteria=failed,
        per_ci=per_ci,
        teacher_question=_teacher_question(band, failed),
        task_type=task_type,
    )


def log_decision(decision: Decision, task_id=None, actor="AUTO"):
    """Append the decision to PortalFeatureLog + JSONL audit (Rule 9)."""
    import json, datetime
    from pathlib import Path
    from exams.models import PortalFeatureLog

    key = "mizan.decision." + (str(task_id) if task_id else "adhoc")
    PortalFeatureLog.objects.create(
        key=key, old_enabled=False,
        new_enabled=(decision.band in (BAND_AUTO_APPROVE,
                                       BAND_AUTO_APPROVE_WITH_NOTE)),
        changed_by=None,
        note=("band=" + decision.band
              + " cs=" + str(decision.cs)
              + " failed=" + ",".join(decision.failed_criteria)),
    )
    line = {
        "ts": datetime.datetime.utcnow().isoformat() + "Z",
        "task_id": task_id,
        "task_type": decision.task_type,
        "cs": decision.cs,
        "band": decision.band,
        "per_ci": decision.per_ci,
        "failed": decision.failed_criteria,
        "actor": actor,
    }
    out = Path("/home/orkoworo/idealogy/tmp/mizan_decisions.jsonl")
    with open(out, "a", encoding="utf-8") as f:
        f.write(json.dumps(line) + "\n")
    return line


# ---------------------------------------------------------------------------
# P13-6: Correction-specific criteria (C8, C9). C1-C7 unchanged.
# C8: the specific defect is resolved (corrected_value non-blank and != current)
# C9: sibling-consistency (no conflict with rows sharing the same parent)
# Standards: ISO 8000-8 5.2-5.5; DAMA-DMBOK2 Ch.13; Rule H; Rule 28.
# ---------------------------------------------------------------------------
CORRECTION_WEIGHTS = {"C8": 0.60, "C9": 0.40}


def _evaluate_correction_ci(ai_output, context):
    per_ci = {"C8": 0, "C9": 0}
    new = str((ai_output or {}).get("corrected_value") or "").strip()
    cur = str((ai_output or {}).get("current_value") or "").strip()
    if new and new != cur:
        per_ci["C8"] = 1
    if (ai_output or {}).get("sibling_consistent") is True or context.get("no_siblings"):
        per_ci["C9"] = 1
    return per_ci


def decide_correction(ai_output, context=None):
    ctx = dict(context or {})
    base = _evaluate_ci("DATA_CORRECTION", ai_output or {}, ctx)
    corr = _evaluate_correction_ci(ai_output or {}, ctx)
    per_ci = dict(base); per_ci.update(corr)
    if not str((ai_output or {}).get("framework_ref") or "").strip():
        per_ci["C1"] = 0
    cs = 0.0
    for k, w in CORRECTION_WEIGHTS.items():
        if per_ci.get(k) == 1:
            cs += w
    cs = round(cs, 4)
    if per_ci.get("C1") == 0 or per_ci.get("C8") == 0 or per_ci.get("C7") == 0:
        band = BAND_REFUSE_WITH_ROUTE
    elif cs >= 0.90:
        band = BAND_AUTO_APPROVE
    elif cs >= 0.60:
        band = BAND_AUTO_APPROVE_WITH_NOTE
    else:
        band = BAND_HITL
    failed = [k for k, v in per_ci.items() if v == 0]
    return Decision(cs=cs, band=band, action_text=ACTION_TEXT[band],
                    provisional=(band == BAND_REFUSE_WITH_ROUTE),
                    failed_criteria=failed, per_ci=per_ci,
                    teacher_question=_teacher_question(band, failed),
                    task_type="DATA_CORRECTION")
