"""student_task_dispatch - Rule 10 dispatcher for the Student Task Queue.

Maps task_type -> (prompt source, canonical writer). Never forks a writer.
Never invents a prompt (Rule 11: the prompt is the printer output or the
file on disk).

Design: design/PROP-2026-10-07-STUDENT-TASK-QUEUE-v3.1.md Section 4.
Standards: Rule 10; Rule 11; Rule H (student-authored KC content stored
  teacher_approved=False; G5 gate unchanged); ISO 21500:2021 4.3.3;
  ISO 9001:2015 7.5.3.
"""
import json
from dataclasses import dataclass
from io import StringIO
from pathlib import Path

from django.conf import settings
from django.core.management import call_command
from django.utils import timezone

from exams.models import StudentTask


PROMPTS_DIR = Path("/home/orkoworo/idealogy/prompts")
STUDENT_PROMPTS = PROMPTS_DIR / "student"
TMP_DIR = Path("/home/orkoworo/idealogy/tmp/student_tasks")


@dataclass
class DispatchResult:
    ok: bool
    error: str = ""
    message: str = ""
    canonical_command: str = ""
    payload_path: str = ""


def _write_payload(task_id, payload):
    TMP_DIR.mkdir(parents=True, exist_ok=True)
    p = TMP_DIR / (str(task_id) + ".json")
    p.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
    return p


def _capture(command, *args, **kwargs):
    buf = StringIO()
    call_command(command, *args, stdout=buf, **kwargs)
    return buf.getvalue()


# --------------------------------------------------------------------------
# Prompt sources (Rule 11: printer output or file on disk, never invented)
# --------------------------------------------------------------------------

def _prompt_book_ingest(task, payload):
    """BOOK_INGEST: use the student subject prompt from prompts/student/.
    Subject inferred from task.task_ref like 'CH-9-P40#p=1-2' or payload.code.
    """
    code = (payload.get("code") or "").upper()
    if not code:
        # derive from task_ref: strip "#p=..." fragment; take the first token
        ref = (task.task_ref or "").split("#", 1)[0].strip().upper()
        code = ref
    prefix = code.split("-")[0] if code else ""
    subject_map = {
        "MT": "science_v5.md", "PH": "science_v5.md", "CH": "science_v5.md",
        "BI": "science_v5.md", "CS": "science_v5.md",
        "EN": "english_v6.md",
        "UR": "urdu_unsolved_v1.md",
        "IS": "islamiyat_v2.md",
        "TQ": "tarjumatul_quran_v1.md",
    }
    fname = subject_map.get(prefix, "science_v5.md")
    p = STUDENT_PROMPTS / fname
    if not p.exists():
        raise FileNotFoundError("student prompt not found: " + str(p))
    return p.read_text(encoding="utf-8")


def _prompt_kc_misconception(task, payload):
    """KC_MISCONCEPTION: printer make_kc_prompt <kc_code>.

    Defence-in-depth guard (added 2026-10-08). Refuses if the KC's
    subject is not in the student's enrolled subjects. The assignment
    guard in views.py stops new bad rows; this guard stops any bad row
    that reaches the prompt layer by any other path.

    Standards: NIST SP 800-53 SI-10 (reject invalid input);
    Saltzer & Schroeder 1975 (fail-safe default = deny);
    AERA/APA/NCME 2014 Std 1.0 (construct must match reported
    subject); Rule 12 (Mizan must gate, not fall back).
    """
    from exams.models import KnowledgeComponent, StudentTask as _ST, Exam as _EX

    kc_code = task.task_ref
    kc = KnowledgeComponent.objects.filter(code=kc_code).first()
    if not kc:
        raise ValueError("KC not found: " + str(kc_code))

    subject_to_prefix = {
        "Mathematics": "MT", "Physics": "PH", "Chemistry": "CH",
        "Biology": "BI", "English": "EN", "Urdu": "UR",
        "Islamiyat": "IS", "Computer Science": "CS",
        "Tarjumatul Quran": "TQ",
    }
    kc_prefix = subject_to_prefix.get(kc.subject or "", "")
    if not kc_prefix:
        raise ValueError(
            "KC subject not mapped: " + repr(kc.subject)
        )

    # Option A gate: check the pipeline's book subject, not the student's
    # academic enrollment. Enrollment governs Taleem ka Safar (academic
    # study, Section 23.13). System K Kaam book-building is per-book,
    # assigned by the boss/helper model (Section 3 team-lead). These are
    # two different things and must not be conflated.
    # A Chemistry KC on a Math book pipeline is refused; a Math KC on a
    # Math book pipeline is accepted regardless of the student's electives.
    # Standards: NIST SP 800-53 SI-10 (reject invalid input at boundary);
    # Saltzer & Schroeder 1975 (fail-safe default = deny);
    # Rule 14 (task categories stay pure); Rule 28 (standards supremacy).
    pipe = task.pipeline
    if pipe is None:
        raise ValueError(
            "KC_MISCONCEPTION refused: task " + str(task.id)
            + " has no pipeline (cannot verify subject scope)"
        )
    book_prefix = ((pipe.paper_code or "").split("-")[0] or "").strip().upper()
    if not book_prefix:
        raise ValueError(
            "KC_MISCONCEPTION refused: pipeline paper_code '"
            + str(pipe.paper_code) + "' has no subject prefix"
        )
    if kc_prefix != book_prefix:
        raise ValueError(
            "KC_MISCONCEPTION refused: KC subject " + kc.subject
            + " (" + kc_prefix + ") does not match pipeline book "
            + str(pipe.paper_code) + " (" + book_prefix + ")"
        )

    return _capture("make_kc_prompt", kc_code)


def _prompt_kc_socratic_ladder(task, payload):
    from exams.models import KnowledgeComponent
    kc = KnowledgeComponent.objects.filter(code=(task.task_ref or '').strip()).first()
    if not kc:
        raise ValueError('KC not found: ' + str(task.task_ref))
    p = PROMPTS_DIR / 'MASTER_KC_SOCRATIC_LADDER_PROMPT.md'
    s = p.read_text(encoding='utf-8')
    s = s.replace('__KC_CODE__', kc.code or '')
    s = s.replace('__KC_TITLE__', kc.title or '')
    s = s.replace('__KC_SUBJECT__', kc.subject or '')
    s = s.replace('__KC_CHAPTER__', kc.chapter or '')
    s = s.replace('__KC_DESCRIPTION__', kc.description or '')
    s = s.replace('__KC_COGNITIVE_LEVEL__', kc.cognitive_level or 'UND')
    lines = []
    for m in (kc.misconceptions or []):
        if isinstance(m, dict) and m.get('cycle_consistent') is not False:
            lines.append('Candidate ' + str(m.get('index', '?')) + ':')
            lines.append('  misconception: ' + (m.get('text') or ''))
            lines.append('  faulty_reasoning: ' + (m.get('faulty_reasoning') or ''))
            lines.append('  incorrect_answer: ' + (m.get('incorrect_answer') or ''))
            lines.append('')
    s = s.replace('__SURVIVORS__', '\n'.join(lines).rstrip() or '(none)')
    return s


def _prompt_glossary(task, payload):
    """GLOSSARY: prompt from KC key_terms, batched 30 per submission.

    Payload may supply {"words": [...]}; else terms are read from
    the KC referenced by task.task_ref. Batch progress is tracked in
    task.json_payload (Sweller CLT: 30 terms = one working-memory load).
    Standards: ISO/IEC/IEEE 29119-3 5.4; Rule 10; AERA Std 1.0.
    """
    from exams.models import KnowledgeComponent
    BATCH_SIZE = 30

    words = list(payload.get("words") or [])
    if not words:
        kc = KnowledgeComponent.objects.filter(code=task.task_ref).first()
        if not kc or not kc.key_terms:
            # User-friendly Roman Urdu message (Rule G; WCAG 2.2 SC 3.3.1).
            # Student sees plain text; no Python traceback.
            raise ValueError(
                "Is KC par abhi alfaaz maujood nahi. Teacher ko batayein. "
                "(KC " + str(task.task_ref) + ")"
            )
        # Only terms needing enrichment; if all enriched, use all terms
        needs = [t["term"] for t in kc.key_terms
                 if isinstance(t, dict) and t.get("term")
                 and (not t.get("definition") or not t.get("roman_urdu"))]
        all_terms = [t["term"] for t in kc.key_terms
                     if isinstance(t, dict) and t.get("term")]
        words = needs or all_terms

    # Read-only. Batch advancement happens ONLY in the writer on success.
    # Standards: Rule 10 (one writer); ISO/IEC/IEEE 29119-3 5.4.
    jp = task.json_payload or {}
    start = int(jp.get("glossary_batch_start", 0))
    total = len(words)
    batch = words[start:start + BATCH_SIZE]

    if not batch:
        raise ValueError(
            f"GLOSSARY: all {total} terms processed. Task should be marked DONE."
        )

    # Persist ONLY the total (idempotent), never advance the pointer here.
    if jp.get("glossary_total") != total:
        jp["glossary_total"] = total
        jp["glossary_batch_index"] = (start // BATCH_SIZE) + 1
        jp["glossary_batches_total"] = (total + BATCH_SIZE - 1) // BATCH_SIZE
        task.json_payload = jp
        task.save(update_fields=["json_payload"])

    return _capture("make_glossary_prompt", *batch)


def _prompt_kc_tag(task, payload):
    """KC_TAG: printer make_kc_tag_prompt <paper_code>.

    Refuses with a clear message if the target subject has no KCs.
    Standards: NIST SP 800-53 SI-10 (reject invalid input);
    Rule H (no diagnostic claim without a construct); arXiv 2025
    conversational misreferencing (never hand the model a mismatched list).
    """
    from exams.models import KnowledgeComponent
    paper_code = (task.task_ref or "").strip().upper()
    if not paper_code:
        raise ValueError("KC_TAG task_ref must be a paper code")
    # subject resolution mirrors make_kc_tag_prompt
    prefix = paper_code.split("-")[0].upper()
    subject_map = {
        "MT": "Mathematics", "PH": "Physics", "CH": "Chemistry",
        "BI": "Biology", "EN": "English", "UR": "Urdu",
        "IS": "Islamiyat", "CS": "Computer Science", "TQ": "Tarjumatul Quran",
    }
    subject = subject_map.get(prefix, "General")
    if subject != "General":
        exists = KnowledgeComponent.objects.filter(
            is_active=True, subject__iexact=subject
        ).exists()
        if not exists and subject == "Chemistry":
            exists = KnowledgeComponent.objects.filter(
                is_active=True, code__startswith="C9-CH"
            ).exists()
        if not exists:
            raise ValueError(
                "KC_TAG not dispatchable: no KnowledgeComponents exist for "
                "subject=" + subject + ". The KC list for this subject has "
                "not been built yet. Ask the teacher to seed KCs first."
            )
    return _capture("make_kc_tag_prompt", paper_code)


def _prompt_handwriting_en(task, payload):
    """HANDWRITING_EN: static practice instruction (Roman Urdu).

    Standards: Rule G (Roman Urdu); DASH-2; Vander Hart 2010;
    HANDWRITING-SPEC-v1.0 s3 (daily 10-12 min, compulsory);
    IN-11 (kalma analogy).
    """
    return (
        "AAJ KI LIKHAI MASHQ (English)\n"
        "\n"
        "1. Apni copy aur pen nikalein.\n"
        "2. 10 minute tak likhein (ghari dekh lein).\n"
        "3. Har letter saaf likhein. Jaldi nahi karni.\n"
        "4. Likhai ke baad apna behtareen letter circle karein.\n"
        "5. Neeche \'Mashq mukammal\' dabayein.\n"
        "\n"
        "Yaad rakhein: Jaisay kalma imaan ki kunji hai, waise hi\n"
        "saaf likhai board exam ki kunji hai."
    )


def _prompt_handwriting_ur(task, payload):
    """HANDWRITING_UR: Nastaliq practice instruction (Roman Urdu).

    Standards: IEEE Access 2024 (Nastaliq pedagogy);
    HANDWRITING-SPEC-v1.0 s5.2 (single -> alternate -> ligature);
    Rule G.
    """
    return (
        "AAJ KI LIKHAI MASHQ (Urdu Nastaliq)\n"
        "\n"
        "1. Apni Urdu copy nikalein.\n"
        "2. 10 minute tak Nastaliq likhein.\n"
        "3. Har harf ka aakar aur flow dhyan se likhein.\n"
        "4. Likhai ke baad apna behtareen harf circle karein.\n"
        "5. Neeche \'Mashq mukammal\' dabayein.\n"
        "\n"
        "Yaad rakhein: Jaisay kalma imaan ki kunji hai, waise hi\n"
        "saaf Nastaliq board exam ki kunji hai."
    )


def _prompt_reading_en(task, payload):
    """READING_EN: oral reading + comprehension probe instruction.

    Standards: Hasbrouck & Tindal 2017 (ORF); NAEP 2026 (4 targets);
    READING-SPEC-v1.0 s3 (monthly probe); Rule G.
    """
    return (
        "AAJ KI READING PROBE (English)\n"
        "\n"
        "1. Apni English book ka ek page khol lein.\n"
        "2. 1 minute tak buland awaaz mein parhein.\n"
        "3. Har lafz saaf aur theek bola jaye.\n"
        "4. Phir teacher 4 sawal poochenge. Unke jawab likhein.\n"
        "5. Neeche \'Mashq mukammal\' dabayein."
    )


def _prompt_reading_ur(task, payload):
    """READING_UR: Urdu oral reading probe instruction.

    Standards: Hasbrouck & Tindal 2017 methodology;
    READING-SPEC-v1.0 s3.4 (Urdu ORF); Rule G.
    """
    return (
        "AAJ KI READING PROBE (Urdu)\n"
        "\n"
        "1. Apni Urdu kitab ka ek sabaq khol lein.\n"
        "2. 1 minute tak buland awaaz mein parhein.\n"
        "3. Har lafz saaf aur theek bola jaye.\n"
        "4. Phir teacher kuch sawal poochenge.\n"
        "5. Neeche \'Mashq mukammal\' dabayein."
    )


def _prompt_unsupported(task, payload):
    raise NotImplementedError(
        "printer not built for " + task.task_type
        + " - add a make_* command before enabling this task type"
    )


def _prompt_kc_discovery(task, payload):
    """KC_DISCOVERY: printer make_kc_discovery_prompt <paper_code>.
    task.task_ref is the subject bank code (e.g. MT-9, not MT-9-BOOK)."""
    paper_code = (task.task_ref or "").strip().upper()
    if paper_code.endswith("-BOOK"):
        paper_code = paper_code[:-5]
    if not paper_code:
        raise ValueError("KC_DISCOVERY task_ref must be a subject bank code")
    return _capture("make_kc_discovery_prompt", paper_code)




def _prompt_story(task):
    """STORY: MASTER_STORY_PROMPT.md + filled INPUTS for this KC."""
    from datetime import date
    from pathlib import Path
    from exams.models import KnowledgeComponent
    kc = KnowledgeComponent.objects.filter(code=task.task_ref).first()
    if not kc:
        raise ValueError(f"STORY: KC not found: {task.task_ref}")
    prompt_file = Path.home() / "idealogy" / "prompts" / "MASTER_STORY_PROMPT.md"
    base = prompt_file.read_text(encoding="utf-8")
    inputs = (
        "\n\n---\n\nFILLED INPUTS\n\n"
        f"teaching_date: {date.today().isoformat()}\n"
        f"subject: {getattr(kc, 'subject', '')}\n"
        f"chapter: {getattr(kc, 'chapter', '')}\n"
        f"kc_code: {kc.code}\n"
        f"question: {getattr(kc, 'title', kc.code)}\n"
        "stories_requested: 1\n"
    )
    return base + inputs


def _writer_story(task, payload, actor=None):
    """STORY: invoke ingest_stories on the student's JSON reply."""
    import json, tempfile, os
    from io import StringIO
    from django.core.management import call_command
    if not payload:
        raise ValueError("STORY: empty payload")
    fd, path = tempfile.mkstemp(suffix=".json", prefix="story_")
    try:
        with os.fdopen(fd, "w") as f:
            json.dump(payload, f)
        out = StringIO()
        call_command("ingest_stories", path, stdout=out, stderr=out)
        return {"ok": True, "output": out.getvalue()[:500]}
    finally:
        try: os.unlink(path)
        except Exception: pass


PROMPT_SOURCES = {
    "BOOK_INGEST": _prompt_book_ingest,
    "KC_DISCOVERY": _prompt_kc_discovery,
    "KC_MISCONCEPTION": _prompt_kc_misconception,
    "KC_TAG": _prompt_kc_tag,
    "KC_SOCRATIC_LADDER": _prompt_kc_socratic_ladder,
    "GLOSSARY": _prompt_glossary,
    "STORY": _prompt_story,
    # Phase 4 (2026-10-08): handwriting + reading
    "HANDWRITING_EN": _prompt_handwriting_en,
    "HANDWRITING_UR": _prompt_handwriting_ur,
    "READING_EN": _prompt_reading_en,
    "READING_UR": _prompt_reading_ur,
}


# --------------------------------------------------------------------------
# Canonical writers (Rule 10)
# --------------------------------------------------------------------------

def _writer_book_ingest(task, payload, json_path):
    """BOOK_INGEST: normalize -BOOK suffix, then ingest_model_paper.

    Task refs use EN-9-BOOK (internal pipeline marker); ingest_model_paper
    expects EN-9 (subject bank). Normalize payload.code before dispatch.
    Standards: Rule 10; NIST SP 800-53 SI-10; RFC 761 (Postel).
    """
    import json
    from pathlib import Path as _P
    p = _P(json_path)
    try:
        data = json.loads(p.read_text(encoding="utf-8"))
        code = (data.get("code") or "").strip()
        if code.endswith("-BOOK"):
            data["code"] = code[:-5]
            code = data["code"]
        # Derive subject from code prefix if the payload omitted it.
        if not data.get("subject") and not data.get("paper", {}).get("subject"):
            SUBJECT_MAP = {
                "MT": "Mathematics", "PH": "Physics", "CH": "Chemistry",
                "BI": "Biology", "EN": "English", "UR": "Urdu",
                "IS": "Islamiyat", "CS": "Computer Science", "TQ": "Tarjumatul Quran",
            }
            pref = code.split("-")[0].upper() if code else ""
            if pref in SUBJECT_MAP:
                data["subject"] = SUBJECT_MAP[pref]
        p.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
    except Exception:
        pass  # fall through; ingest_model_paper will report its own errors
    call_command("ingest_model_paper", str(p), subject_bank=True)
    return "ingest_model_paper " + str(p) + " --subject-bank"


def _writer_kc_misconception(task, payload, json_path):
    kc_code = task.task_ref
    call_command("generate_kc_content", kc_code,
                 generation_file=str(json_path))
    # Rule H: student-authored content must be teacher_approved=False.
    # generate_kc_content already writes teacher_approved=False for new entries.
    return "generate_kc_content " + kc_code + " --generation-file " + str(json_path)


def _writer_kc_socratic_ladder(task, payload, json_path):
    kc_code = task.task_ref
    # Student at stage 5 supplies ladders[] only. Misconceptions were
    # already stored by stage 4. Rule 10: canonical writer is
    # generate_kc_content with only --ladder-file.
    call_command("generate_kc_content", kc_code,
                 ladder_file=str(json_path))
    return "generate_kc_content " + kc_code + " --ladder-file " + str(json_path)


def _writer_glossary(task, payload, json_path):
    """GLOSSARY writer: ingest_terms (Rule 10 sole writer for key_terms).

    Advances batch; marks task DONE when all batches completed.
    Standards: ISO/IEC/IEEE 29119-3 5.4; Rule 10; Rule 9.
    """
    kc_code = payload.get("kc_code") or task.task_ref or "C9-CH00-GLOSSARY"
    call_command("ingest_terms", kc_code, terms_file=str(json_path))

    # Advance batch pointer on success only (Rule 10).
    jp = task.json_payload or {}
    start = int(jp.get("glossary_batch_start", 0))
    total = int(jp.get("glossary_total", 0))
    BATCH_SIZE = 30
    new_start = start + BATCH_SIZE
    jp["glossary_batch_start"] = new_start
    jp["glossary_batch_index"] = (new_start // BATCH_SIZE)
    jp["glossary_batches_total"] = (total + BATCH_SIZE - 1) // BATCH_SIZE if total else 0
    task.json_payload = jp
    if total and new_start >= total:
        task.status = "DONE"
        task.save(update_fields=["json_payload", "status"])
        return f"ingest_terms {kc_code} [all {total} terms done]"
    task.save(update_fields=["json_payload"])
    return f"ingest_terms {kc_code} [batch {jp['glossary_batch_index']}/{jp['glossary_batches_total']}]"


def _writer_kc_tag(task, payload, json_path):
    paper_code = (task.task_ref or "").strip().upper()
    if not paper_code:
        raise ValueError("KC_TAG task_ref must be a paper code")
    call_command("kc_tag", str(json_path), bank=paper_code, strict=False)
    return "kc_tag " + str(json_path) + " --bank " + paper_code


def _writer_kc_discovery(task, payload, json_path):
    """KC_DISCOVERY writer: validate shape, store proposal, DO NOT create KCs.

    Rule 10: seed_kcs remains the sole writer of KnowledgeComponent. This
    writer stores the proposal in the task's json_payload; the teacher gate
    (stage 4) calls seed_kcs to promote approved KCs.
    """
    if not isinstance(payload, dict):
        raise ValueError("KC_DISCOVERY payload must be a JSON object")
    kcs = payload.get("kcs")
    if not isinstance(kcs, list) or not kcs:
        raise ValueError("KC_DISCOVERY payload must contain a non-empty kcs[] list")
    # validate each entry minimally
    ALIASES = {
        "code":        ("code", "kc_id", "id"),
        "title":       ("title", "name"),
        "description": ("description", "desc"),
    }
    for i, k in enumerate(kcs, 1):
        if not isinstance(k, dict):
            raise ValueError("kcs[" + str(i) + "] must be an object")
        # Normalize aliases into canonical field names (schema-evolution standard)
        for canon, opts in ALIASES.items():
            if k.get(canon):
                continue
            for alt in opts:
                if k.get(alt):
                    k[canon] = k[alt]
                    break
        for f in ("code", "title", "description"):
            if not k.get(f):
                raise ValueError(
                    "kcs[" + str(i) + "] missing field: " + f
                    + " (accepted aliases: "
                    + ", ".join(ALIASES[f]) + ")"
                )
    # store proposal on the task; caller persists
    task.json_payload = payload
    task.save(update_fields=["json_payload"])
    return "KC_DISCOVERY proposal stored on task " + str(task.id) + " (" + str(len(kcs)) + " KCs)"


def _writer_handwriting(task, payload, json_path):
    """HANDWRITING_*: student marks practice done. No DB write here.

    The formal assessment is a separate teacher action via `assess_skill`.
    Standards: Rule 10 (one writer); HANDWRITING-SPEC-v1.0 s3.
    """
    return ("handwriting practice recorded on task " + str(task.id)
            + " (awaiting weekly assessment)")


def _writer_reading(task, payload, json_path):
    """READING_*: student marks reading probe done. No DB write here.

    The formal assessment is a separate teacher action via `assess_skill`.
    Standards: Rule 10; READING-SPEC-v1.0 s3.
    """
    return ("reading probe recorded on task " + str(task.id)
            + " (awaiting teacher scoring)")


WRITERS = {
    "BOOK_INGEST": _writer_book_ingest,
    "KC_DISCOVERY": _writer_kc_discovery,
    "KC_MISCONCEPTION": _writer_kc_misconception,
    "KC_TAG": _writer_kc_tag,
    "KC_SOCRATIC_LADDER": _writer_kc_socratic_ladder,
    "GLOSSARY": _writer_glossary,
    "STORY": _writer_story,
    # Phase 4 (2026-10-08): handwriting + reading
    "HANDWRITING_EN": _writer_handwriting,
    "HANDWRITING_UR": _writer_handwriting,
    "READING_EN": _writer_reading,
    "READING_UR": _writer_reading,
}


def get_prompt(task):
    """Rule 11: return the exact text the student pastes into the AI."""
    src = PROMPT_SOURCES.get(task.task_type)
    if not src:
        raise NotImplementedError("unknown task_type: " + task.task_type)
    return src(task, task.json_payload or {})


def dispatch(task):
    """Call the canonical writer for task.task_type. Assumes task.json_payload
    is already parsed and set. Returns DispatchResult."""
    w = WRITERS.get(task.task_type)
    if w is None:
        return DispatchResult(
            ok=False,
            error="task_type " + task.task_type + " is not dispatchable yet "
                  "(printer not built). See proposal v3.1 Section 4.",
        )
    payload = task.json_payload or {}
    try:
        json_path = _write_payload(task.id, payload)
    except Exception as e:
        return DispatchResult(ok=False, error="payload write failed: " + str(e))

    try:
        cmd = w(task, payload, json_path)
    except Exception as e:
        return DispatchResult(
            ok=False,
            error=type(e).__name__ + ": " + str(e)[:300],
            payload_path=str(json_path),
        )
    finally:
        try:
            Path(json_path).unlink(missing_ok=True)
        except Exception:
            pass

    if isinstance(cmd, DispatchResult):
        return cmd
    return DispatchResult(ok=True, canonical_command=cmd, payload_path=str(json_path))



def _prompt_data_correction(task, payload):
    from exams.models import DataQualityIssue
    from pathlib import Path
    iid = (task.task_ref or "").replace("DQ-", "").strip()
    issue = DataQualityIssue.objects.filter(pk=int(iid)).first() if iid.isdigit() else None
    if not issue:
        return "[NO DEFECT for task_ref=" + (task.task_ref or "?") + "]"
    tmpl = (Path.home() / "idealogy" / "prompts" / "MASTER_KC_CORRECTION_PROMPT.md").read_text(encoding="utf-8")
    ctx = "Entity: " + issue.entity_type + " #" + str(issue.entity_id) + chr(10)
    ctx += "Defect: " + issue.defect_class + " (" + issue.severity + ")" + chr(10)
    ctx += "Evidence: " + str(issue.evidence)
    return tmpl.replace("__DEFECT_CONTEXT__", ctx)


def _writer_data_correction_inner(task, payload, json_path=None):
    from exams.models import (DataQualityIssue, ModelQuestion,
                              ModelPaper, KnowledgeComponent, CorrectionLog)
    from django.utils import timezone
    from django.db import transaction
    from exams.kc_firewall import sanctioned_context
    iid = (task.task_ref or "").replace("DQ-", "").strip()
    if not iid.isdigit():
        return DispatchResult(ok=False, error="task_ref not DQ-<id>")
    issue = DataQualityIssue.objects.filter(pk=int(iid)).first()
    if not issue:
        return DispatchResult(ok=False, error="no DQ issue #" + iid)
    if issue.status in ("CLOSED", "VERIFIED"):
        return DispatchResult(ok=False, error="issue already " + issue.status)
    field = (payload.get("field") or "").strip()
    new_val = (payload.get("corrected_value") or "").strip()
    fref = (payload.get("framework_ref") or "").strip()
    if not (field and new_val and fref):
        return DispatchResult(ok=False, error="field/corrected_value/framework_ref required")

    ENT = {"ModelQuestion": ModelQuestion,
           "ModelPaper": ModelPaper,
           "KnowledgeComponent": KnowledgeComponent}
    M = ENT.get(issue.entity_type)
    if not M:
        return DispatchResult(ok=False, error="unknown entity_type: " + issue.entity_type)
    with sanctioned_context("data_correction"):
        with transaction.atomic():
            obj = M.objects.filter(pk=issue.entity_id).first()
            if not obj:
                return DispatchResult(ok=False, error="entity vanished")
            old_val = str(getattr(obj, field, ""))
            # Two repair modes (standards: ALCOA+ Original; ISO 8000-61):
            #   MALFORMED    -> edit in place (typo fix).
            #   DUPLICATE    -> supersede (mark old; history preserved).
            #   INCONSISTENT -> supersede (wrong row retired).
            if issue.defect_class == "MALFORMED":
                setattr(obj, field, new_val)
                obj.save(update_fields=[field])
            else:
                if hasattr(obj, "superseded_at"):
                    obj.superseded_at = timezone.now()
                    obj.save(update_fields=["superseded_at"])
                else:
                    return DispatchResult(ok=False,
                        error="entity has no superseded_at: " + issue.entity_type)
            CorrectionLog.objects.create(
                kind="MODEL", target_model=issue.entity_type,
                target_id=issue.entity_id, field_name=field,
                old_value=old_val, new_value=new_val, reason=fref,
                actor=task.student.student_user if task.student.student_user else None,
                actor_label="data_correction:" + str(task.id),
            )
            issue.status = "VERIFIED"
            issue.resolved_at = timezone.now()
            issue.resolved_by_task = task
            issue.save(update_fields=["status", "resolved_at", "resolved_by_task"])
    return DispatchResult(ok=True, error="")

PROMPT_SOURCES["DATA_CORRECTION"] = _prompt_data_correction

def _writer_data_correction(task, payload, json_path=None):
    """Wrapper: run inner; on failure bump attempt_count; escalate at 3."""
    from exams.models import DataQualityIssue
    result = _writer_data_correction_inner(task, payload, json_path)
    iid = (task.task_ref or "").replace("DQ-", "").strip()
    issue = DataQualityIssue.objects.filter(pk=int(iid)).first() if iid.isdigit() else None
    if issue is None:
        return result
    if result.ok:
        return result
    issue.attempt_count = (issue.attempt_count or 0) + 1
    if issue.attempt_count >= 3 and issue.status != "VERIFIED":
        issue.status = "ESCALATED"
        issue.save(update_fields=["attempt_count", "status"])
        return DispatchResult(ok=False, error=result.error +
            " [3 attempts reached; escalated to teacher queue]")
    issue.save(update_fields=["attempt_count"])
    return result

WRITERS["DATA_CORRECTION"] = _writer_data_correction
