"""Wizard views for the 7-gate KC content pipeline (admin-only).

Standards: Nielsen Norman Group - wizards suit occasional processes;
Cooper Stage-Gate - each gate is a go/kill/hold decision;
Django docs, staff_member_required - admin-only views;
Django docs, The admin site - "if you need a more process-centric
interface that abstracts away the implementation details of database
tables and fields, then it's probably time to write your own views"
(decisive: custom views, not ModelAdmin);
OWASP ASVS 4.3.1 (admin interface authentication),
4.3.2 (directory browsing off),
4.3.3 (step-up auth on high-value actions - G6);
OWASP ASVS 5.1.3 (input validation); ASVS 5.3 (output encoding);
CWE-78 (command injection - subprocess with list, shell=False);
NIST SP 800-53 SI-10 (information input validation);
WCAG 2.2 AA (SC 3.3.7 no redundant entry; SC 1.4.3 contrast);
EU AI Act Art.14 (meaningful human oversight - G5);
ISO/IEC 42001 (AI management - log every action);
ISO 9241-210 (human-centred design);
ISO 27001 A.8.15 (change logging);
Rule 9 (audit logs append-only); Rule 10 (one canonical path);
Rule 11 (prompt mandatory).
"""
import datetime
import io
import json
import re
import subprocess
import sys
import uuid
from pathlib import Path as _Path

from django.contrib.admin.views.decorators import staff_member_required
from django.core.management import call_command
from django.shortcuts import render

from .models import KnowledgeComponent


PROMPT_SCRIPT = _Path("/home/orkoworo/idealogy/scripts/make_model_prompt.py")
CODE_RE = re.compile(r"^[A-Z0-9][A-Z0-9-]{0,29}$")
WIZARD_KEY = "kc_wizard"

# Gate metadata (order + label + whether it is implemented)
GATES = [
    ("g1", "G1 Paper intake", True),
    ("g2", "G2 Ingest", True),
    ("g3", "G3 KC tagging", False),
    ("g4", "G4 Misconception generation", True),
    ("g5", "G5 Human approval", True),
    ("g6", "G6 Prompt freeze", True),
    ("g7", "G7 Daily report", True),
]


def _wizard_state(request):
    """Return the per-session wizard state dict (created empty if absent)."""
    return request.session.setdefault(WIZARD_KEY, {})


def _gate_context(request, current):
    """Common context for every gate template."""
    return {
        "gates": GATES,
        "current": current,
        "state": _wizard_state(request),
    }


@staff_member_required
def home(request):
    """Wizard landing: shows the 7 gates and current session state."""
    ctx = _gate_context(request, current="home")
    return render(request, "exams/wizard/home.html", ctx)


STUDENT_PROMPTS_DIR = _Path("/home/orkoworo/idealogy/prompts/student")
SUBJECT_PROMPT_MAP = {
    "MT-9-P": "science_v5.md",
    "PH-9-P": "science_v5.md",
    "CH-9-P": "science_v5.md",
    "BI-9-P": "science_v5.md",
    "CS-9-P": "science_v5.md",
    "EN-9-P": "english_v6.md",
    "UR-9-P": "urdu_unsolved_v1.md",
    "IS-9-P": "islamiyat_v2.md",
    "TQ-9-P": "tarjumatul_quran_v1.md",
}


BOOK_PREFIXES = {
    "MT-9-P": {"subject": "Mathematics", "medium": "EN", "book": "Hamdard Mathematics 9"},
    "CH-9-P": {"subject": "Chemistry", "medium": "EN", "book": "Hamdard Chemistry 9"},
    "PH-9-P": {"subject": "Physics", "medium": "EN", "book": "Hamdard Physics 9"},
    "BI-9-P": {"subject": "Biology", "medium": "EN", "book": "Hamdard Biology 9"},
    "EN-9-P": {"subject": "English", "medium": "EN", "book": "Hamdard English 9"},
    "UR-9-P": {"subject": "Urdu", "medium": "UR", "book": "Hamdard Urdu 9"},
    "IS-9-P": {"subject": "Islamiyat", "medium": "EN", "book": "Hamdard Islamiyat 9"},
    "CS-9-P": {"subject": "Computer Science", "medium": "EN", "book": "Hamdard Computer Science 9"},
    "TQ-9-P": {"subject": "Tarjumatul Quran", "medium": "UR", "book": "Hamdard Tarjumatul Quran 9"},
}


def _resolve_book_from_code(code):
    for prefix, info in BOOK_PREFIXES.items():
        if code.startswith(prefix):
            return prefix, info
    return None, None


@staff_member_required
def g1_intake(request):
    """G1 - Paper intake. One input (paper code); everything else derived.

    The code prefix (CH-9-P, PH-9-P, ...) tells the system the subject,
    medium, book title, and source note. Teacher types one code; gets one
    prompt. GOV.UK "only ask for what you cannot infer"; Nielsen NN
    recognition over recall.
    """
    state = _wizard_state(request)
    error = None
    prompt_text = ""
    code_value = ""
    book_value = ""
    paper_num_value = ""
    if request.method == "POST":
        # Session 8: dropdown book + number input (was: single free-text code).
        # Legacy 'code' still accepted as fallback so old bookmarks work.
        legacy_code = (request.POST.get("code") or "").strip().upper()
        book_value = (request.POST.get("book") or "").strip().upper()
        paper_num_value = (request.POST.get("paper_num") or "").strip()
        if book_value and paper_num_value:
            try:
                _pn = int(paper_num_value)
                if 1 <= _pn <= 99:
                    code_value = book_value + str(_pn).zfill(2)
                else:
                    error = "Paper number 1 se 99 ke darmiyan hona chahiye."
            except (TypeError, ValueError):
                error = "Paper number sirf angka mein likhein (misal 39)."
        elif legacy_code:
            code_value = legacy_code
        prefix, info = _resolve_book_from_code(code_value)

        if not CODE_RE.match(code_value):
            error = "Code ka format ghalat hai. Misal: CH-9-P39."
        elif not info:
            error = ("Yeh prefix pehchani nahi gayi. In mein se ek honi chahiye: "
                     + ", ".join(BOOK_PREFIXES.keys()) + ".")
        else:
            # Session 9: route to the subject-specific student prompt.
            _prompt_file_name = SUBJECT_PROMPT_MAP.get(prefix)
            if not _prompt_file_name:
                error = ("Is subject ke liye student prompt mojood nahi. "
                         "Prefix: " + prefix)
            else:
                _path = STUDENT_PROMPTS_DIR / _prompt_file_name
                if not _path.exists():
                    error = "Student prompt file not found: " + str(_path)
                else:
                    try:
                        prompt_text = _path.read_text(encoding="utf-8")
                    except Exception as exc:
                        error = "Prompt file read error: " + str(exc)
                    else:
                        # Substitute the example code with the teacher's real code.
                        # Each student prompt contains an example like "CH-9-P24"
                        # inside the JSON shape; replace only that first occurrence.
                        for _example in ("CH-9-P24", "EN-9-P16", "UR-9-P15",
                                         "IS-9-P18", "TQ-9-P05"):
                            if _example in prompt_text:
                                prompt_text = prompt_text.replace(
                                    _example, code_value, 1)
                                break
                    state["g1"] = {"code": code_value}
                    request.session.modified = True

    ctx = _gate_context(request, current="g1")
    ctx["error"] = error
    ctx["prompt_text"] = prompt_text
    ctx["form"] = state.get("g1", {})
    ctx["book_prefixes"] = list(BOOK_PREFIXES.keys())
    ctx["book_map"] = BOOK_PREFIXES
    ctx["code_value"] = code_value
    ctx["book_value"] = book_value
    ctx["paper_num_value"] = paper_num_value
    return render(request, "exams/wizard/g1_intake.html", ctx)


@staff_member_required
def g2_ingest(request):
    """G2 - Ingest. Paste Gemini JSON -> ingest_model_paper.

    Standards: Django docs, call_command (programmatic invocation;
    avoids CWE-78 shell injection); OWASP ASVS 4.3.1 (admin-only via
    staff_member_required); OWASP ASVS 5.1.3 (input validation);
    NIST SP 800-53 SI-10; WCAG 2.2 AA (SC 3.3.1, 3.3.3, 1.4.3, 2.4.1);
    ISO 9001:2015 7.5.3 (documented information - audit log);
    Rule 9 (log first, delete second);
    Rule 10 (one canonical path - reuse the file-based command).
    """
    state = _wizard_state(request)
    error = None
    output = ""
    pasted = ""
    tmp_path = None

    if request.method == "POST":
        pasted = (request.POST.get("payload") or "").strip()
        strict = bool(request.POST.get("strict"))
        subject_bank = bool(request.POST.get("subject_bank"))
        if not pasted:
            error = "Paste the Gemini JSON first."
        else:
            tmp_dir = _Path("/home/orkoworo/idealogy/tmp")
            try:
                tmp_dir.mkdir(parents=True, exist_ok=True)
                token = uuid.uuid4().hex[:12]
                tmp_path = tmp_dir / ("g2_paste_" + token + ".json")
                tmp_path.write_text(pasted, encoding="utf-8")

                out_buf = io.StringIO()
                err_buf = io.StringIO()
                ingest_error = None
                try:
                    call_command(
                        "ingest_model_paper",
                        str(tmp_path),
                        strict=strict,
                        subject_bank=subject_bank,
                        stdout=out_buf,
                        stderr=err_buf,
                    )
                except Exception as exc:
                    ingest_error = str(exc)

                output = out_buf.getvalue() + err_buf.getvalue()

                audit = {
                    "ts": datetime.datetime.now(datetime.UTC).isoformat(),
                    "gate": "g2",
                    "user": request.user.username,
                    "strict": strict,
                    "subject_bank": subject_bank,
                    "bytes": len(pasted),
                    "ingest_ok": ingest_error is None,
                    "ingest_error": ingest_error,
                    "output": output,
                }
                audit_path = tmp_dir / (
                    "g2_ingest_"
                    + datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ")
                    + "_"
                    + token
                    + ".json"
                )
                audit_path.write_text(json.dumps(audit, indent=2), encoding="utf-8")

                state["g2"] = {"ok": ingest_error is None, "audit": str(audit_path)}
                request.session.modified = True

                if ingest_error:
                    error = "Ingest failed: " + ingest_error
            except Exception as exc:
                error = "G2 error: " + str(exc)
            finally:
                try:
                    if tmp_path is not None and tmp_path.exists():
                        tmp_path.unlink()
                except Exception:
                    pass

    ctx = _gate_context(request, current="g2")
    ctx["error"] = error
    ctx["output"] = output
    ctx["pasted"] = pasted
    return render(request, "exams/wizard/g2_ingest.html", ctx)


@staff_member_required
def g3_kc_tag(request):
    """G3 - KC tagging. Paste a Q-matrix JSON -> kc_tag.

    Standards: Tatsuoka (1983) Rule Space - Q-matrix maps items to
    knowledge components; Buck et al. (1998); de la Torre & Chiu (2016);
    Templin & Hoffman (2013) - initial Q-matrix from expert judgment,
    not data; arXiv 2604.16398 (2026) - AI tags are hypotheses pending
    expert review; AERA/APA/NCME 2014 Std 13.7 (each stored kc_code
    names its KC); Django docs, call_command (in-process; CWE-78
    avoided); OWASP ASVS 4.3.1 (admin-only); OWASP ASVS 5.1.3 (input
    validation); NIST SP 800-53 SI-10; WCAG 2.2 AA (SC 3.3.1, 3.3.3);
    ISO 9001:2015 7.5.3 (documented information);
    Rule 9 (log first, delete second);
    Rule 10 (one canonical path - reuse kc_tag);
    Rule 11 (KC tagging prompts, if AI-drafted, must exist).
    """
    state = _wizard_state(request)
    error = None
    output = ""
    pasted = ""
    tmp_path = None

    if request.method == "POST":
        pasted = (request.POST.get("payload") or "").strip()
        strict = bool(request.POST.get("strict"))
        dry_run = bool(request.POST.get("dry_run"))
        if not pasted:
            error = "Paste the Q-matrix JSON first."
        else:
            tmp_dir = _Path("/home/orkoworo/idealogy/tmp")
            try:
                tmp_dir.mkdir(parents=True, exist_ok=True)
                token = uuid.uuid4().hex[:12]
                tmp_path = tmp_dir / ("g3_paste_" + token + ".json")
                tmp_path.write_text(pasted, encoding="utf-8")

                out_buf = io.StringIO()
                err_buf = io.StringIO()
                tag_error = None
                try:
                    call_command(
                        "kc_tag",
                        str(tmp_path),
                        strict=strict,
                        dry_run=dry_run,
                        stdout=out_buf,
                        stderr=err_buf,
                    )
                except Exception as exc:
                    tag_error = str(exc)

                output = out_buf.getvalue() + err_buf.getvalue()

                audit = {
                    "ts": datetime.datetime.now(datetime.UTC).isoformat(),
                    "gate": "g3",
                    "user": request.user.username,
                    "strict": strict,
                    "dry_run": dry_run,
                    "bytes": len(pasted),
                    "tag_ok": tag_error is None,
                    "tag_error": tag_error,
                    "output": output,
                }
                audit_path = tmp_dir / (
                    "g3_kc_tag_"
                    + datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ")
                    + "_"
                    + token
                    + ".json"
                )
                audit_path.write_text(json.dumps(audit, indent=2), encoding="utf-8")

                state["g3"] = {"ok": tag_error is None, "audit": str(audit_path)}
                request.session.modified = True

                if tag_error:
                    error = "Tagging failed: " + tag_error
            except Exception as exc:
                error = "G3 error: " + str(exc)
            finally:
                try:
                    if tmp_path is not None and tmp_path.exists():
                        tmp_path.unlink()
                except Exception:
                    pass

    ctx = _gate_context(request, current="g3")
    ctx["error"] = error
    ctx["output"] = output
    ctx["pasted"] = pasted
    return render(request, "exams/wizard/g3_kc_tag.html", ctx)


@staff_member_required
def g4_generate(request):
    """G4 - Misconception generation (three-AI pipeline, four sub-stages).

    Sub-stage 1: enter kc_code + paste Gemini JSON -> make_kc_validation_prompt
    Sub-stage 2: paste ChatGPT JSON   -> make_kc_rerank_prompt
    Sub-stage 3: paste Claude rerank  -> make_kc_socratic_ladder_prompt
    Sub-stage 4: paste Claude ladder  -> generate_kc_content (ingest)

    Standards: MISTAKE (Ross & Andreas, arXiv 2510.11502) cycle
    consistency; Finch-Zk (Goel et al., EMNLP 2025) cross-model
    hallucination detection; A-HMAD heterogeneous multi-agent debate;
    MiRAGE 2025 (retrieve + rerank); ITU-T F.748.52; Kirschner, Sweller &
    Clark (2006) guided instruction; Polya 1945; Sweller et al. 2011;
    Rosenshine 2012; Hattie & Timperley 2007; Wood, Bruner & Ross 1976;
    Vygotsky 1978 ZPD; EU AI Act Art.14 (human approval is G5, not G4);
    NIST AI RMF MEASURE 2.5/2.6; ISO/IEC 42001;
    AERA/APA/NCME 2014 Std 13.7; Django docs call_command;
    OWASP ASVS 4.3.1, 5.1.3; NIST SP 800-53 SI-10; CWE-78 (avoided);
    WCAG 2.2 AA (SC 3.3.1, 3.3.7); ISO 9001:2015 7.5.3;
    Rule 9 (log first, delete second);
    Rule 10 (one canonical path - reuse the four printers + generator);
    Rule 11 (the printer commands emit the exact prompt to paste).
    """
    state = _wizard_state(request)
    g4 = state.get("g4") or {}
    from .models import KnowledgeComponent
    kc_list = list(
        KnowledgeComponent.objects.order_by("code")
        .values("code", "title", "subject")
    )
    tmp_dir = _Path("/home/orkoworo/idealogy/tmp")
    error = None
    output = ""
    prompt_text = ""
    pasted = ""
    action = ""

    def _save(slot, body):
        path = tmp_dir / ("g4_" + g4["token"] + "_" + slot + ".json")
        path.write_text(body, encoding="utf-8")
        return path

    def _audit(event, extra=None):
        rec = {
            "ts": datetime.datetime.now(datetime.UTC).isoformat(),
            "gate": "g4",
            "event": event,
            "user": request.user.username,
            "token": g4.get("token"),
            "kc_code": g4.get("kc_code"),
            "stage": g4.get("stage"),
        }
        if extra:
            rec.update(extra)
        tok = g4.get("token") or uuid.uuid4().hex[:12]
        p = tmp_dir / ("g4_audit_"
                       + datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ")
                       + "_" + tok + ".json")
        p.write_text(json.dumps(rec, indent=2), encoding="utf-8")

    if request.method == "POST":
        action = (request.POST.get("action") or "").strip()

    if action == "restart":
        token = g4.get("token")
        _audit("restart")
        deleted = 0
        if token:
            for slot in ("gen", "val", "rer", "lad"):
                f = tmp_dir / ("g4_" + token + "_" + slot + ".json")
                if f.exists():
                    f.unlink()
                    deleted += 1
        state.pop("g4", None)
        request.session.modified = True
        g4 = {}
        output = "G4 restarted. Deleted " + str(deleted) + " temp file(s)."

    elif action == "get_prompt":
        from .models import KnowledgeComponent
        kc_code = (request.POST.get("kc_code") or "").strip().upper()
        if not kc_code:
            error = "KC code is required."
        else:
            try:
                kc = KnowledgeComponent.objects.get(
                    code=kc_code, is_active=True)
            except KnowledgeComponent.DoesNotExist:
                error = "KC not found: " + kc_code
            else:
                out_buf = io.StringIO(); err_buf = io.StringIO()
                try:
                    call_command("make_kc_prompt", kc_code,
                                 stdout=out_buf, stderr=err_buf)
                except Exception as exc:
                    error = "make_kc_prompt failed: " + str(exc)
                    _audit("get_prompt_fail",
                           {"kc_code": kc_code, "error": str(exc)})
                else:
                    prompt_text = out_buf.getvalue()
                    if err_buf.getvalue():
                        prompt_text = prompt_text + "\n" + err_buf.getvalue()
                    if not g4 or g4.get("kc_code") != kc_code:
                        g4 = {"token": uuid.uuid4().hex[:12],
                              "kc_code": kc_code, "stage": 1, "files": {}}
                        state["g4"] = g4
                        request.session.modified = True
                    _audit("get_prompt_ok",
                           {"kc_code": kc_code,
                            "prompt_len": len(prompt_text)})

    elif action == "submit":
        pasted = (request.POST.get("payload") or "").strip()
        stage = int(g4.get("stage") or 1)
        if not pasted:
            error = "Paste the JSON first."
        elif stage == 1:
            kc_code = (request.POST.get("kc_code") or "").strip().upper()
            if not kc_code:
                error = "KC code is required at sub-stage 1."
            else:
                g4 = {"token": uuid.uuid4().hex[:12], "kc_code": kc_code,
                      "stage": 1, "files": {}}
                gen_path = _save("gen", pasted)
                g4["files"]["gen"] = str(gen_path)
                out_buf = io.StringIO(); err_buf = io.StringIO()
                try:
                    call_command("make_kc_validation_prompt", kc_code,
                                 generation_file=str(gen_path),
                                 stdout=out_buf, stderr=err_buf)
                    prompt_text = out_buf.getvalue() + err_buf.getvalue()
                    g4["stage"] = 2
                    state["g4"] = g4
                    request.session.modified = True
                    _audit("stage1_ok", {"output_len": len(prompt_text)})
                except Exception as exc:
                    error = "Sub-stage 1 failed: " + str(exc)
                    _audit("stage1_fail", {"error": str(exc)})
        elif stage == 2:
            val_path = _save("val", pasted)
            g4["files"]["val"] = str(val_path)
            out_buf = io.StringIO(); err_buf = io.StringIO()
            try:
                call_command("make_kc_rerank_prompt", g4["kc_code"],
                             generation_file=g4["files"]["gen"],
                             validation_file=str(val_path),
                             stdout=out_buf, stderr=err_buf)
                prompt_text = out_buf.getvalue() + err_buf.getvalue()
                g4["stage"] = 3
                state["g4"] = g4
                request.session.modified = True
                _audit("stage2_ok", {"output_len": len(prompt_text)})
            except Exception as exc:
                error = "Sub-stage 2 failed: " + str(exc)
                _audit("stage2_fail", {"error": str(exc)})
        elif stage == 3:
            rer_path = _save("rer", pasted)
            g4["files"]["rer"] = str(rer_path)
            out_buf = io.StringIO(); err_buf = io.StringIO()
            try:
                call_command("make_kc_socratic_ladder_prompt", g4["kc_code"],
                             generation_file=g4["files"]["gen"],
                             validation_file=g4["files"]["val"],
                             rerank_file=str(rer_path),
                             stdout=out_buf, stderr=err_buf)
                prompt_text = out_buf.getvalue() + err_buf.getvalue()
                g4["stage"] = 4
                state["g4"] = g4
                request.session.modified = True
                _audit("stage3_ok", {"output_len": len(prompt_text)})
            except Exception as exc:
                error = "Sub-stage 3 failed: " + str(exc)
                _audit("stage3_fail", {"error": str(exc)})
        elif stage == 4:
            dry_run = bool(request.POST.get("dry_run"))
            lad_path = _save("lad", pasted)
            g4["files"]["lad"] = str(lad_path)
            out_buf = io.StringIO(); err_buf = io.StringIO()
            try:
                call_command("generate_kc_content", g4["kc_code"],
                             generation_file=g4["files"]["gen"],
                             validation_file=g4["files"]["val"],
                             rerank_file=g4["files"]["rer"],
                             ladder_file=str(lad_path),
                             dry_run=dry_run,
                             stdout=out_buf, stderr=err_buf)
                output = out_buf.getvalue() + err_buf.getvalue()
                _audit("stage4_ok", {"dry_run": dry_run,
                                     "output_len": len(output)})
                if not dry_run:
                    deleted = 0
                    for slot in ("gen", "val", "rer", "lad"):
                        f = tmp_dir / ("g4_" + g4["token"] + "_" + slot + ".json")
                        if f.exists():
                            f.unlink()
                            deleted += 1
                    state.pop("g4", None)
                    request.session.modified = True
                    g4 = {}
                    output = output + "\nG4 complete. Deleted " + str(deleted) + " temp file(s)."
            except Exception as exc:
                error = "Sub-stage 4 failed: " + str(exc)
                _audit("stage4_fail", {"error": str(exc), "dry_run": dry_run})

    stage_now = int(g4.get("stage") or 1)
    ctx = _gate_context(request, current="g4")
    ctx["error"] = error
    ctx["output"] = output
    ctx["prompt_text"] = prompt_text
    ctx["pasted"] = pasted
    ctx["g4"] = g4
    ctx["stage"] = stage_now
    ctx["kc_list"] = kc_list
    return render(request, "exams/wizard/g4_generate.html", ctx)


@staff_member_required
def g5_approve(request):
    """G5 - Human approval gate. Teacher approves / edits / rejects.

    The only teacher touchpoint in the pipeline.
    Actions:
      approve_all   - mark every misconception + ladder entry approved
      save_edits    - apply inline edits and the per-row approved checkbox
      reject_reset  - clear both lists on the KC; ready_for_diagnosis=False

    G5 does NOT flip ready_for_diagnosis. That is G6 (see the
    KnowledgeComponent docstring).

    Standards: EU AI Act Art.14 (meaningful human oversight is a
    mandatory gate); ISO/IEC 42001 Clause 7.5 (documented decisions);
    ISO 9001:2015 7.5.3 (audit trail); AERA/APA/NCME 2014 Std 13.7
    (teacher_approved names the construct); WCAG 2.2 AA (SC 3.3.1,
    3.3.3, 3.3.7); OWASP ASVS 4.3.1 (admin-only); OWASP ASVS 5.1.3
    (input validation); NIST SP 800-53 SI-10;
    Rule 9 (log first, delete second); Rule 10 (one canonical path).
    """
    state = _wizard_state(request)
    tmp_dir = _Path("/home/orkoworo/idealogy/tmp")
    error = None
    message = ""

    kc_list = list(KnowledgeComponent.objects.order_by("code"))
    kc_code = (request.POST.get("kc_code") or request.GET.get("kc") or "").strip().upper()
    kc = None
    for k in kc_list:
        if k.code == kc_code:
            kc = k
            break

    action = (request.POST.get("action") or "").strip() if request.method == "POST" else ""

    def _audit(event, extra=None):
        rec = {
            "ts": datetime.datetime.now(datetime.UTC).isoformat(),
            "gate": "g5",
            "event": event,
            "user": request.user.username,
            "kc_code": kc.code if kc else None,
        }
        if extra:
            rec.update(extra)
        token = uuid.uuid4().hex[:12]
        path = tmp_dir / ("g5_audit_"
                          + datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ")
                          + "_" + token + ".json")
        path.write_text(json.dumps(rec, indent=2), encoding="utf-8")

    if kc and action == "approve_all":
        mcs = list(kc.misconceptions or [])
        lads = list(kc.socratic_ladder or [])
        for m in mcs:
            m["teacher_approved"] = True
        for l in lads:
            l["teacher_approved"] = True
        kc.misconceptions = mcs
        kc.socratic_ladder = lads
        kc.save(update_fields=["misconceptions", "socratic_ladder", "updated_at"])
        _audit("approve_all", {"misconceptions": len(mcs), "ladders": len(lads)})
        message = "Approved all entries on " + kc.code + "."

    elif kc and action == "reject_reset":
        before_mc = len(kc.misconceptions or [])
        before_lad = len(kc.socratic_ladder or [])
        kc.misconceptions = []
        kc.socratic_ladder = []
        kc.ready_for_diagnosis = False
        kc.save(update_fields=[
            "misconceptions", "socratic_ladder",
            "ready_for_diagnosis", "updated_at",
        ])
        _audit("reject_reset",
               {"misconceptions_cleared": before_mc, "ladders_cleared": before_lad})
        message = ("Rejected on " + kc.code + ". Both lists cleared; "
                   "re-run G4 to regenerate.")

    elif kc and action == "save_edits":
        mcs = list(kc.misconceptions or [])
        lads = list(kc.socratic_ladder or [])
        errors = []
        for idx, m in enumerate(mcs):
            pf = "mc_" + str(idx) + "_"
            m["text"] = (request.POST.get(pf + "text") or "").strip()
            m["faulty_reasoning"] = (request.POST.get(pf + "faulty_reasoning") or "").strip()
            m["incorrect_answer"] = (request.POST.get(pf + "incorrect_answer") or "").strip()
            m["teacher_approved"] = (request.POST.get(pf + "approved") == "1")
            if not m["text"]:
                errors.append("Misconception " + str(idx + 1) + " text is empty.")
        for l_idx, l in enumerate(lads):
            lf = "lad_" + str(l_idx) + "_"
            l["teacher_approved"] = (request.POST.get(lf + "approved") == "1")
            steps = list(l.get("steps") or [])
            for s_idx, s in enumerate(steps):
                sf = "lad_" + str(l_idx) + "_s_" + str(s_idx) + "_"
                s["question"] = (request.POST.get(sf + "question") or "").strip()
                s["hint"] = (request.POST.get(sf + "hint") or "").strip()
                s["expected_response"] = (request.POST.get(sf + "expected_response") or "").strip()
                s["worked_example"] = (request.POST.get(sf + "worked_example") or "").strip()
                if not s["question"]:
                    errors.append("Ladder " + str(l_idx + 1) + " step "
                                  + str(s_idx + 1) + " question is empty.")
            l["steps"] = steps
        if errors:
            error = " / ".join(errors[:5])
        else:
            kc.misconceptions = mcs
            kc.socratic_ladder = lads
            kc.save(update_fields=["misconceptions", "socratic_ladder", "updated_at"])
            _audit("save_edits",
                   {"misconceptions": len(mcs), "ladders": len(lads)})
            message = "Saved edits on " + kc.code + "."

    if kc:
        mcs = list(kc.misconceptions or [])
        lads = list(kc.socratic_ladder or [])
        mc_ap = sum(1 for m in mcs if m.get("teacher_approved"))
        lad_ap = sum(1 for l in lads if l.get("teacher_approved"))
        all_approved = bool(mcs) and bool(lads) and mc_ap == len(mcs) and lad_ap == len(lads)
    else:
        mcs = lads = []
        mc_ap = lad_ap = 0
        all_approved = False

    ctx = _gate_context(request, current="g5")
    ctx["error"] = error
    ctx["message"] = message
    ctx["kc_list"] = kc_list
    ctx["kc"] = kc
    ctx["misconceptions"] = mcs
    ctx["ladders"] = lads
    ctx["mc_approved"] = mc_ap
    ctx["lad_approved"] = lad_ap
    ctx["all_approved"] = all_approved
    return render(request, "exams/wizard/g5_approve.html", ctx)


@staff_member_required
def g6_freeze(request):
    """G6 - Prompt freeze. Flip ready_for_diagnosis=True on a KC.

    Preconditions (enforced):
      - KC has at least one misconception
      - KC has at least one ladder
      - every misconception entry has teacher_approved=True
      - every ladder entry has teacher_approved=True
      - the POST carries confirm=1 (explicit second step)

    Actions:
      confirm    - flip ready_for_diagnosis=True (all gates must pass)
      unfreeze   - flip ready_for_diagnosis=False (escape hatch)

    Step-up decision (OWASP ASVS 4.3.3):
      The standard permits either additional authentication or
      restriction to a designated subset of users. Idealogy has a
      single designated staff user, gated by @staff_member_required
      (ASVS 4.3.1). The lighter "extra confirmation" form is used:
      a confirm checkbox + POST-only. A password re-prompt would add
      teacher minutes without materially improving security for a
      21-student closed cohort (see Section 15.4, time cap).

    Standards: Cooper Stage-Gate (this is the freeze decision);
    EU AI Act Art.14 (final human confirmation);
    OWASP ASVS 4.3.1 (admin-only), 4.3.3 (step-up decision above),
    5.1.3 (input validation); NIST SP 800-53 SI-10;
    AERA/APA/NCME 2014 Std 13.7 (ready_for_diagnosis names its
    construct); ISO/IEC 42001 Clause 7.5; ISO 9001:2015 7.5.3;
    WCAG 2.2 AA (SC 3.3.1, 3.3.3);
    Rule 9 (log first, delete second); Rule 10 (one canonical path).
    """
    tmp_dir = _Path("/home/orkoworo/idealogy/tmp")
    error = None
    message = ""

    kc_list = list(KnowledgeComponent.objects.order_by("code"))
    kc_code = (request.POST.get("kc_code") or request.GET.get("kc") or "").strip().upper()
    kc = None
    for k in kc_list:
        if k.code == kc_code:
            kc = k
            break

    action = (request.POST.get("action") or "").strip() if request.method == "POST" else ""

    def _audit(event, extra=None):
        rec = {
            "ts": datetime.datetime.now(datetime.UTC).isoformat(),
            "gate": "g6",
            "event": event,
            "user": request.user.username,
            "kc_code": kc.code if kc else None,
        }
        if extra:
            rec.update(extra)
        token = uuid.uuid4().hex[:12]
        path = tmp_dir / ("g6_audit_"
                          + datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ")
                          + "_" + token + ".json")
        path.write_text(json.dumps(rec, indent=2), encoding="utf-8")

    if kc and action == "confirm":
        mcs = list(kc.misconceptions or [])
        lads = list(kc.socratic_ladder or [])
        mc_unapproved = sum(1 for m in mcs if not m.get("teacher_approved"))
        lad_unapproved = sum(1 for l in lads if not l.get("teacher_approved"))
        confirmed = (request.POST.get("confirm") == "1")
        if not mcs or not lads:
            error = "G6 requires at least one misconception and one ladder."
            _audit("confirm_blocked", {"reason": "missing_lists"})
        elif mc_unapproved or lad_unapproved:
            error = ("Cannot freeze: " + str(mc_unapproved) + " misconception(s) "
                     "and " + str(lad_unapproved) + " ladder(s) not approved. "
                     "Go back to G5.")
            _audit("confirm_blocked",
                   {"mc_unapproved": mc_unapproved, "lad_unapproved": lad_unapproved})
        elif not confirmed:
            error = "Tick the confirm checkbox to proceed."
            _audit("confirm_blocked", {"reason": "no_confirm_tick"})
        else:
            kc.ready_for_diagnosis = True
            kc.save(update_fields=["ready_for_diagnosis", "updated_at"])
            _audit("frozen", {"misconceptions": len(mcs), "ladders": len(lads)})
            message = "Frozen. " + kc.code + " is now ready_for_diagnosis=True."

    elif kc and action == "unfreeze":
        kc.ready_for_diagnosis = False
        kc.save(update_fields=["ready_for_diagnosis", "updated_at"])
        _audit("unfrozen")
        message = "Unfrozen. " + kc.code + " is now ready_for_diagnosis=False."

    if kc:
        mcs = list(kc.misconceptions or [])
        lads = list(kc.socratic_ladder or [])
        mc_ap = sum(1 for m in mcs if m.get("teacher_approved"))
        lad_ap = sum(1 for l in lads if l.get("teacher_approved"))
        can_freeze = (bool(mcs) and bool(lads)
                      and mc_ap == len(mcs) and lad_ap == len(lads))
    else:
        mcs = lads = []
        mc_ap = lad_ap = 0
        can_freeze = False

    ctx = _gate_context(request, current="g6")
    ctx["error"] = error
    ctx["message"] = message
    ctx["kc_list"] = kc_list
    ctx["kc"] = kc
    ctx["mc_count"] = len(mcs)
    ctx["lad_count"] = len(lads)
    ctx["mc_approved"] = mc_ap
    ctx["lad_approved"] = lad_ap
    ctx["can_freeze"] = can_freeze
    return render(request, "exams/wizard/g6_freeze.html", ctx)


@staff_member_required
def g7_report(request):
    """G7 - Daily report. Paste grading JSON -> ingest_reports [--pdf].

    Produces Submission rows, PDF report cards, and a ZIP in
    ~/idealogy/output/daily_reports/. WhatsApp delivery stays manual
    (Section A of the guide: not a live API; teacher sends the PDFs).

    Standards: Wiggins & McTighe 2005 (assessment informs next step);
    Hattie & Timperley 2007 (feed-forward feedback);
    Guskey, On Your Mark 3rd ed. 2020 (reporting to parents);
    ESSA Report Card Design (at-a-glance summary);
    AERA/APA/NCME 2014 Std 13.7 (stored values name their construct);
    ISO 9001:2015 7.5.3 (documented information - audit per POST);
    Django docs call_command (in-process; CWE-78 avoided);
    OWASP ASVS 4.3.1 (admin-only), 5.1.3 (input validation);
    NIST SP 800-53 SI-10; WCAG 2.2 AA (SC 3.3.1, 3.3.3);
    Rule 8 (no YouTube URLs in PDFs; Roman Urdu only - enforced by
    the command and by exams/pdf.py);
    Rule 9 (log first, delete second); Rule 10 (one canonical path).
    """
    tmp_dir = _Path("/home/orkoworo/idealogy/tmp")
    out_dir = _Path("/home/orkoworo/idealogy/output/daily_reports")
    error = None
    output = ""
    pasted = ""
    produced = []
    tmp_path = None

    if request.method == "POST":
        pasted = (request.POST.get("payload") or "").strip()
        make_pdf = bool(request.POST.get("pdf"))
        if not pasted:
            error = "Paste the grading JSON first."
        else:
            try:
                tmp_dir.mkdir(parents=True, exist_ok=True)
                token = uuid.uuid4().hex[:12]
                tmp_path = tmp_dir / ("g7_paste_" + token + ".json")
                tmp_path.write_text(pasted, encoding="utf-8")

                before = set()
                if out_dir.exists():
                    before = {f.name for f in out_dir.iterdir() if f.is_file()}

                out_buf = io.StringIO()
                err_buf = io.StringIO()
                ingest_error = None
                try:
                    call_command(
                        "ingest_reports",
                        str(tmp_path),
                        pdf=make_pdf,
                        stdout=out_buf,
                        stderr=err_buf,
                    )
                except Exception as exc:
                    ingest_error = str(exc)

                output = out_buf.getvalue() + err_buf.getvalue()

                if out_dir.exists():
                    after = {f.name for f in out_dir.iterdir() if f.is_file()}
                    for name in sorted(after - before):
                        f = out_dir / name
                        produced.append({
                            "name": name,
                            "size": f.stat().st_size,
                            "path": str(f),
                        })

                audit = {
                    "ts": datetime.datetime.now(datetime.UTC).isoformat(),
                    "gate": "g7",
                    "user": request.user.username,
                    "pdf": make_pdf,
                    "bytes": len(pasted),
                    "ingest_ok": ingest_error is None,
                    "ingest_error": ingest_error,
                    "produced": [x["name"] for x in produced],
                    "output": output,
                }
                audit_path = tmp_dir / (
                    "g7_ingest_"
                    + datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ")
                    + "_" + token + ".json"
                )
                audit_path.write_text(json.dumps(audit, indent=2), encoding="utf-8")

                if ingest_error:
                    error = "Ingest failed: " + ingest_error
            except Exception as exc:
                error = "G7 error: " + str(exc)
            finally:
                try:
                    if tmp_path is not None and tmp_path.exists():
                        tmp_path.unlink()
                except Exception:
                    pass

    ctx = _gate_context(request, current="g7")
    ctx["error"] = error
    ctx["output"] = output
    ctx["pasted"] = pasted
    ctx["produced"] = produced
    ctx["out_dir"] = str(out_dir)
    return render(request, "exams/wizard/g7_report.html", ctx)
