"""writer_e2e_test — exercise one task-type writer end-to-end.

Runs the writer with a synthetic fixture, checks DB side-effects, then
ROLLS BACK unless --apply is given. Safe on prod by default.

Standards: ISO/IEC/IEEE 29119-3 6 (test execution); Rule 4; Rule 26.
"""
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from exams.models import (Student, StudentTask, ModelQuestion,
                          KnowledgeComponent)


def _fixture_kc_tag(paper_code):
    # Take the first 3 live questions of that bank, tag with any KC
    kc = KnowledgeComponent.objects.filter(is_active=True).first()
    if not kc:
        raise CommandError("no KC in DB for tagging")
    qs = ModelQuestion.objects.filter(
        paper__code=paper_code, superseded_at__isnull=True,
    ).order_by("question_index")[:3]
    tags = []
    for q in qs:
        tags.append({
            "paper_code": paper_code,
            "question_index": q.question_index,
            "kc_code": kc.code,
        })
    return {"tags": tags}, kc.code


def _fixture_glossary(task):
    return {"key_terms": [{
        "term": "_e2e_test_term_zzz",
        "roman_urdu": "_e2e_test_roman",
        "definition": "_e2e synthetic definition",
        "example": "_e2e synthetic example",
        "non_example": "_e2e synthetic non_example",
        "probes": {"receptive": "?", "discrimination": "?", "productive": "?"},
        "confidence": 0.5,
    }]}


def _fixture_kc_misconception(task):
    return {"candidates": [{
        "misconception": "_e2e synthetic misconception",
        "faulty_reasoning": "_e2e faulty reasoning",
        "incorrect_answer": "_e2e wrong answer",
        "confidence": 0.5,
    }]}


def _fixture_kc_socratic_ladder(task):
    # generate_kc_content --ladder-file expects ladders[] keyed by
    # misconception_index. Shape mirrors MASTER_KC_SOCRATIC_LADDER_PROMPT.
    return {
        "ladders": [{
            "misconception_index": 1,
            "steps": [
                {"order": 1, "polya_phase": "UNDERSTAND", "question": "_e2e q1"},
                {"order": 2, "polya_phase": "PLAN", "question": "_e2e q2"},
                {"order": 3, "polya_phase": "EXECUTE", "question": "_e2e q3"},
                {"order": 4, "polya_phase": "REFLECT", "question": "_e2e q4"},
            ],
        }],
    }


def _fixture_kc_discovery(task):
    return {
        "kcs": [{"code": "C9-E2E99-TEST", "title": "_e2e", "description": "_e2e"}],
        "unassigned_questions": [],
    }


def _fixture_book_ingest(task):
    paper_code = (task.task_ref or "").split("#")[0].strip()
    SUBJECT_MAP = {"MT": "Mathematics", "PH": "Physics", "CH": "Chemistry",
                   "BI": "Biology", "EN": "English", "UR": "Urdu",
                   "IS": "Islamiyat", "CS": "Computer Science",
                   "TQ": "Tarjumatul Quran"}
    pref = paper_code.split("-")[0].upper()
    return {
        "code": paper_code,
        "subject": SUBJECT_MAP.get(pref, "General"),
        "title": "_e2e book title",
        "questions": [{
            "question_index": 32000,  # PositiveSmallInteger max = 32767
            "question_text": "_e2e question text",
            "model_answer": "_e2e model",
        }],
    }


FIXTURES = {
    "KC_TAG": _fixture_kc_tag,
    "GLOSSARY": _fixture_glossary,
    "KC_MISCONCEPTION": _fixture_kc_misconception,
    "KC_SOCRATIC_LADDER": _fixture_kc_socratic_ladder,
    "KC_DISCOVERY": _fixture_kc_discovery,
    "BOOK_INGEST": _fixture_book_ingest,
    "HANDWRITING_EN": lambda t: {},
    "HANDWRITING_UR": lambda t: {},
    "READING_EN": lambda t: {},
    "READING_UR": lambda t: {},
}


class Command(BaseCommand):
    help = "Test one writer end-to-end with rollback."

    def add_arguments(self, parser):
        parser.add_argument("--student", required=True)
        parser.add_argument("--task-type", required=True)
        parser.add_argument("--apply", action="store_true")

    def handle(self, *args, **opts):
        from exams.student_task_dispatch import WRITERS
        code = opts["student"].strip().upper()
        tt = opts["task_type"].strip().upper()
        s = Student.objects.filter(code=code).first()
        if not s:
            raise CommandError("student not found: " + code)
        if tt not in WRITERS or WRITERS[tt] is None:
            raise CommandError("no writer for " + tt)
        task = (StudentTask.objects
                .filter(student=s, task_type=tt)
                .exclude(status__in=["SKIPPED", "DONE"])
                .order_by("id").first())
        if not task:
            self.stdout.write("no open task of type " + tt + " for " + code)
            return
        self.stdout.write(f"task id={task.id} ref={task.task_ref} status={task.status}")

        if tt not in FIXTURES:
            raise CommandError("no fixture for " + tt)
        if tt == "KC_TAG":
            payload, kc_used = FIXTURES[tt](task.task_ref)
            self.stdout.write(f"fixture: {len(payload['tags'])} tags -> KC {kc_used}")
        else:
            payload = FIXTURES[tt](task)
            self.stdout.write(f"fixture: {tt} payload built ({len(str(payload))} bytes)")

        before_qs = list(ModelQuestion.objects.filter(
            paper__code=task.task_ref, superseded_at__isnull=True,
        ).values_list("id", "kc_code"))

        result = {"ok": False, "err": None}
        try:
            with transaction.atomic():
                import json, tempfile, os
                fd, path = tempfile.mkstemp(suffix=".json", prefix="e2e_")
                try:
                    with os.fdopen(fd, "w") as f:
                        json.dump(payload, f)
                    out = WRITERS[tt](task, payload, path)
                    result["ok"] = True
                    result["out"] = str(out)[:200]
                finally:
                    try: os.unlink(path)
                    except Exception: pass

                # capture side-effects
                after_qs = list(ModelQuestion.objects.filter(
                    paper__code=task.task_ref, superseded_at__isnull=True,
                ).values_list("id", "kc_code"))
                changed = sum(1 for b, a in zip(before_qs, after_qs) if b[1] != a[1])
                result["kc_changed"] = changed

                if not opts["apply"]:
                    transaction.set_rollback(True)
                    self.stdout.write("ROLLBACK (dry-run)")
                else:
                    self.stdout.write("COMMITTED")
        except Exception as e:
            result["err"] = str(e)[:200]
            self.stdout.write("WRITER EXCEPTION: " + result["err"])

        self.stdout.write("result: " + str({k: v for k, v in result.items()}))
