"""Ingest one Model Paper (Q&A source library) from Gemini-extracted JSON."""
from pathlib import Path as _Path

from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

from exams.models import ModelPaper, ModelQuestion, make_question_slug
from exams.parsing import extract_json

ALLOWED_MEDIUM = {"EN", "UR"}

_SUBJECT_BANK_TITLES = {
    "MT-9": "Mathematics 9 Question Bank",
    "CH-9": "Chemistry 9 Question Bank",
    "PH-9": "Physics 9 Question Bank",
    "BI-9": "Biology 9 Question Bank",
    "EN-9": "English 9 Question Bank",
    "UR-9": "Urdu 9 Question Bank",
    "IS-9": "Islamiyat 9 Question Bank",
    "CS-9": "Computer Science 9 Question Bank",
    "TQ-9": "Tarjumatul Quran 9 Question Bank",
}


def _subject_prefix(code):
    """CH-9-P25 -> CH-9 ; CH-9 -> CH-9 ; else None."""
    import re as _re
    m = _re.match(r"^([A-Z]{2}-9)(?:-P\d+)?$", (code or "").upper())
    return m.group(1) if m else None


def _clean(value, default=""):
    if value is None:
        return default
    return str(value).strip()


def _int(value, default=0):
    try:
        return int(value)
    except (TypeError, ValueError):
        return default


def _flatten_sections(data):
    """Convert a sections-based JSON into a flat questions list.

    Session 9. Each item in a section becomes one ModelQuestion row,
    with question_index sequential across the whole paper. Preserves
    needs_solving and reference in reasoning_chain so the teacher can
    later match each item with its solved-booklet counterpart.

    Standards: 1EdTech QTI v3.0.1 (one item per question); Open edX
    OEP-68 (Code identifier); Rule 10 (one canonical ingest path).
    """
    sections = data.get("sections") or []
    if not sections:
        return None
    flat = []
    idx = 0
    for sec in sections:
        sec_ref = _clean(sec.get("ref"))
        sec_type = _clean(sec.get("type"))
        sec_prompt = _clean(sec.get("prompt"))
        for item in (sec.get("items") or []):
            idx += 1
            n = item.get("n", idx)
            source_ref = (sec_ref + " (" + str(n) + ")") if sec_ref else str(n)
            qtext = ""
            atext = ""

            if item.get("question"):
                qtext = _clean(item["question"])
                atext = _clean(item.get("answer"))
            elif item.get("verses"):
                qtext = _clean(item["verses"])
                atext = _clean(item.get("answer"))
            elif item.get("passage"):
                qtext = _clean(item["passage"])
                atext = _clean(item.get("answer"))
            elif item.get("arabic"):
                qtext = _clean(item["arabic"])
                atext = _clean(item.get("urdu")
                               or item.get("urdu_translation")
                               or item.get("answer"))
            elif item.get("urdu") and item.get("english"):
                qtext = _clean(item["urdu"])
                atext = _clean(item["english"])
            elif item.get("wrong") and item.get("correct"):
                qtext = _clean(item["wrong"])
                atext = _clean(item["correct"])
            elif item.get("word") and item.get("example"):
                qtext = _clean(item["word"])
                atext = _clean(item["example"])
            elif item.get("option") and item.get("instructions"):
                qtext = _clean(item["instructions"])
                atext = _clean(item.get("answer")
                               or item.get("answer_ref")
                               or "NO_ANSWER_PRINTED")
            elif item.get("text"):
                qtext = _clean(item["text"])
                atext = _clean(item.get("answer") or "NO_ANSWER_PRINTED")
            else:
                qtext = _clean(str(item))
                atext = "NO_ANSWER_PRINTED"

            ref = _clean(item.get("reference") or item.get("answer_ref"))
            needs_solving = bool(item.get("needs_solving"))
            if not atext and ref:
                atext = "REFERENCE: " + ref
            if not atext:
                atext = "NO_ANSWER_PRINTED"

            reasoning_chain = []
            if needs_solving or ref:
                reasoning_chain.append({
                    "needs_solving": needs_solving,
                    "reference": ref,
                })

            flat.append({
                "question_index": idx,
                "question_text": qtext,
                "model_answer": atext,
                "source_ref": source_ref,
                "chapter": "",
                "marks": _int(item.get("marks"), 5),
                "reasoning_chain": reasoning_chain,
            })
    return flat



# --- Subject-code standardization (Session 9) -------------------------
# Rule: 9 canonical subject codes exist. Every incoming code normalizes
# to one of these. Aliases are resolved on ingest.
# Standards: 1EdTech QTI v3.0.1 (canonical identifier);
# Open edX OEP-68 (Code identifier, aliases resolve);
# ISO 8000 (data quality - one canonical form);
# Rule 10 (one canonical path).
CANONICAL_SUBJECT_CODES = {
    "MT-9": "Mathematics",
    "PH-9": "Physics",
    "CH-9": "Chemistry",
    "BI-9": "Biology",
    "EN-9": "English",
    "UR-9": "Urdu",
    "IS-9": "Islamiyat",
    "CS-9": "Computer Science",
    "TQ-9": "Tarjumatul Quran",
}

# Alias prefixes (left) that map to the canonical prefix (right).
# Any code starting with a left-hand key normalizes to the right-hand value.
# Order matters - longest match wins, so put longer aliases first.
_SUBJECT_ALIASES = [
    # Mathematics
    ("MATH-9-P", "MT-9"), ("MATH-9", "MT-9"),
    ("MATHEMATICS-9-P", "MT-9"), ("MATHEMATICS-9", "MT-9"),
    ("MATH9P", "MT-9"), ("MATHS-9-P", "MT-9"), ("MATHS-9", "MT-9"),
    ("MT-9-P", "MT-9"), ("MT-9", "MT-9"), ("MT9P", "MT-9"),
    # Physics
    ("PHYSICS-9-P", "PH-9"), ("PHYSICS-9", "PH-9"),
    ("PHY-9-P", "PH-9"), ("PHY-9", "PH-9"),
    ("PH-9-P", "PH-9"), ("PH-9", "PH-9"), ("PH9P", "PH-9"),
    # Chemistry
    ("CHEMISTRY-9-P", "CH-9"), ("CHEMISTRY-9", "CH-9"),
    ("CHEM-9-P", "CH-9"), ("CHEM-9", "CH-9"),
    ("CH-9-P", "CH-9"), ("CH-9", "CH-9"), ("CH9P", "CH-9"),
    # Biology
    ("BIOLOGY-9-P", "BI-9"), ("BIOLOGY-9", "BI-9"),
    ("BIO-9-P", "BI-9"), ("BIO-9", "BI-9"),
    ("BI-9-P", "BI-9"), ("BI-9", "BI-9"), ("BI9P", "BI-9"),
    # English
    ("ENGLISH-9-P", "EN-9"), ("ENGLISH-9", "EN-9"),
    ("ENG-9-P", "EN-9"), ("ENG-9", "EN-9"),
    ("EN-9-P", "EN-9"), ("EN-9", "EN-9"), ("EN9P", "EN-9"),
    # Urdu
    ("URDU-9-P", "UR-9"), ("URDU-9", "UR-9"),
    ("UR-9-P", "UR-9"), ("UR-9", "UR-9"), ("UR9P", "UR-9"),
    # Islamiyat
    ("ISLAMIYAT-9-P", "IS-9"), ("ISLAMIYAT-9", "IS-9"),
    ("ISLAMIAT-9-P", "IS-9"), ("ISLAMIAT-9", "IS-9"),
    ("ISL-9-P", "IS-9"), ("ISL-9", "IS-9"),
    ("IS-9-P", "IS-9"), ("IS-9", "IS-9"), ("IS9P", "IS-9"),
    # Computer Science
    ("COMPUTER SCIENCE-9-P", "CS-9"), ("COMPUTER SCIENCE-9", "CS-9"),
    ("COMPUTER-9-P", "CS-9"), ("COMPUTER-9", "CS-9"),
    ("COMP-9-P", "CS-9"), ("COMP-9", "CS-9"),
    ("CS-9-P", "CS-9"), ("CS-9", "CS-9"), ("CS9P", "CS-9"),
    # Tarjumatul Quran
    ("TARJUMATUL QURAN-9-P", "TQ-9"), ("TARJUMATUL QURAN-9", "TQ-9"),
    ("TARJUMA-9-P", "TQ-9"), ("TARJUMA-9", "TQ-9"),
    ("TQ-9-P", "TQ-9"), ("TQ-9", "TQ-9"), ("TQ9P", "TQ-9"),
]


def standardize_subject_code(raw_code):
    """Return (canonical_code, was_changed) for any incoming code.

    Output shape (Session 9, corrected):
      bank form   : "CH-9"       (no paper number)
      paper form  : "CH-9-P25"   (digits present -> paper marker kept)
      numbers are zero-padded to 2 digits.

    Scans the alias table; the longest matching prefix wins. Falls back
    to the original code (with was_changed=False) when no alias matches.
    """
    import re as _re
    if not raw_code:
        return ("", False)
    norm = str(raw_code).strip().upper()
    for alias, canonical in _SUBJECT_ALIASES:
        if not norm.startswith(alias):
            continue
        # Already canonical?
        if norm == canonical:
            return (norm, False)
        if norm.startswith(canonical + "-P"):
            return (norm, False)
        # Extract the trailing number from the remainder after the alias.
        tail = norm[len(alias):]
        digits = _re.findall(r"\d+", tail)
        if digits:
            num = digits[-1].zfill(2)
            return (canonical + "-P" + num, True)
        # No digits: bank form.
        return (canonical, True)
    return (norm, False)

class Command(BaseCommand):
    help = "Ingest one Model Paper JSON. Creates ModelPaper + ModelQuestion rows."

    def add_arguments(self, parser):
        parser.add_argument("json_file", type=str)
        parser.add_argument("--strict", action="store_true",
                            help="Reject the whole paper if any question is invalid.")
        parser.add_argument("--subject-bank", action="store_true",
                            help="Append questions to a subject-level bank (e.g. CH-9) "
                                 "instead of a per-paper container. Question indexes "
                                 "are assigned sequentially from the current max.")

    def handle(self, *args, **options):
        path = options["json_file"]
        strict = options["strict"]
        try:
            raw = _Path(path).read_text(encoding="utf-8")
        except FileNotFoundError:
            raise CommandError("File not found: " + path)
        try:
            data = extract_json(raw)
        except ValueError as exc:
            raise CommandError("Invalid JSON: " + str(exc))

        # Accept two shapes (Session 9):
        #   A) nested:  {"paper": {"code": "...", ...}, "questions": [...]}
        #   B) flat:    {"code": "...", "title": "...", "questions": [...]}
        # Student prompts emit shape B; G2 wizard emits shape A.
        paper_in = data.get("paper") or {}

        def _pick(key, default=""):
            v = paper_in.get(key)
            if v in (None, ""):
                v = data.get(key)
            return _clean(v, default)

        code = _pick("code")
        subject = _pick("subject")
        medium = _pick("medium", "EN").upper()
        title = _pick("title")
        source_note = _pick("source_note")

        # Derive subject + medium from code prefix if missing (shape B).
        _PREFIX_MAP = {
            "MT-9-P": ("Mathematics", "EN"),
            "CH-9-P": ("Chemistry", "EN"),
            "PH-9-P": ("Physics", "EN"),
            "BI-9-P": ("Biology", "EN"),
            "EN-9-P": ("English", "EN"),
            "UR-9-P": ("Urdu", "UR"),
            "IS-9-P": ("Islamiyat", "EN"),
            "CS-9-P": ("Computer Science", "EN"),
            "TQ-9-P": ("Tarjumatul Quran", "UR"),
        }
        if code and (not subject or not paper_in.get("medium")):
            for _pfx, (_sub, _med) in _PREFIX_MAP.items():
                if code.upper().startswith(_pfx):
                    if not subject:
                        subject = _sub
                    if not paper_in.get("medium") and not data.get("medium"):
                        medium = _med
                    break

        # Session 9: --subject-bank folds every chunk into a subject bank.
        if options.get("subject_bank") and code:
            _bank = _subject_prefix(code)
            if not _bank:
                raise CommandError(
                    "Cannot derive subject bank from code: " + code
                    + ". Expected format like CH-9-P25 or CH-9.")
            code = _bank
            title = _SUBJECT_BANK_TITLES.get(_bank, _bank + " Question Bank")
            source_note = source_note or "Subject-level bank (Session 9)"

        # Session 9: canonicalize subject code before anything else.
        if code:
            _canon, _changed = standardize_subject_code(code)
            if _changed:
                self.stdout.write("Code normalized: " + code + " -> " + _canon)
            code = _canon

        if not code:
            raise CommandError("paper.code (or top-level code) is required.")
        if not subject:
            raise CommandError("paper.subject (or top-level subject, or a valid code prefix) is required.")
        if medium not in ALLOWED_MEDIUM:
            raise CommandError("paper.medium must be EN or UR, got: " + medium)

        questions = data.get("questions") or []
        if not questions:
            questions = _flatten_sections(data)
        if not questions:
            raise CommandError("No questions in input.")

        warnings = 0
        created_q = 0
        updated_q = 0

        with transaction.atomic():
            paper, is_new_paper = ModelPaper.objects.update_or_create(
                code=code,
                defaults={
                    "subject": subject,
                    "medium": medium,
                    "title": title,
                    "source_note": source_note,
                    "total_questions": len(questions),
                },
            )
            paper_tag = "new" if is_new_paper else "updated"
            self.stdout.write("Paper " + code + " (" + subject + ") - " + paper_tag)

            existing_slugs = set(
                ModelQuestion.objects.filter(paper=paper)
                .exclude(question_slug='')
                .values_list('question_slug', flat=True)
            )
            # Session 9: in bank mode, continue numbering from the current max.
            from django.db.models import Max as _Max
            _max = (ModelQuestion.objects.filter(paper=paper)
                    .aggregate(_m=_Max("question_index"))["_m"]) or 0

            for q in questions:
                qi = _max + _int(q.get("question_index"))
                qt = _clean(q.get("question_text"))
                ma = _clean(q.get("model_answer"))
                if not (qi and qt and ma):
                    self.stderr.write("WARN " + code + " Q" + str(qi) + ": incomplete, skipped")
                    warnings += 1
                    if strict:
                        raise CommandError("Strict mode: incomplete question Q" + str(qi))
                    continue
                # DEF-025 fix (2026-10-08): identity is (paper, question_text),
                # not (paper, question_index). Re-ingest is idempotent by construct.
                # Standards: AERA/APA/NCME 2014 Std 1.0; ISO 8000-61; Rule 10.
                obj = ModelQuestion.objects.filter(paper=paper, question_text=qt).first()
                if obj is not None:
                    if ma:
                        obj.model_answer = ma
                    obj.source_ref = _clean(q.get("source_ref"))
                    obj.chapter = _clean(q.get("chapter"))
                    obj.marks = _int(q.get("marks"), 5)
                    obj.kc_code = _clean(q.get("kc_code"))
                    obj.newman_focus = _clean(q.get("newman_focus"))
                    obj.reasoning_chain = q.get("reasoning_chain") or []
                    obj.socratic_ladder = q.get("socratic_ladder") or []
                    obj.save(update_fields=[
                        "model_answer", "source_ref", "chapter", "marks",
                        "kc_code", "newman_focus", "reasoning_chain",
                        "socratic_ladder",
                    ])
                    is_new = False
                else:
                    obj = ModelQuestion.objects.create(
                        paper=paper,
                        question_index=qi,
                        question_text=qt,
                        model_answer=ma or '',
                        source_ref=_clean(q.get("source_ref")),
                        chapter=_clean(q.get("chapter")),
                        marks=_int(q.get("marks"), 2),
                        kc_code=_clean(q.get("kc_code")),
                        newman_focus=_clean(q.get("newman_focus")),
                        reasoning_chain=q.get("reasoning_chain") or [],
                        socratic_ladder=q.get("socratic_ladder") or [],
                    )
                    is_new = True
                if not obj.question_slug:
                    obj.question_slug = make_question_slug(qt, existing_slugs)
                    existing_slugs.add(obj.question_slug)
                    obj.save(update_fields=['question_slug'])

                if is_new:
                    created_q += 1
                else:
                    updated_q += 1

        if options.get("subject_bank"):
            ModelPaper.objects.filter(code=code).update(
                total_questions=ModelQuestion.objects.filter(
                    paper__code=code).count())

        self.stdout.write(self.style.SUCCESS(
            "Paper: " + code
            + " | Questions created: " + str(created_q)
            + ", updated: " + str(updated_q)
            + ", warnings: " + str(warnings)))
