"""Ingest story-lectures from DeepSeek output."""
import re
from datetime import date
from pathlib import Path as _Path

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

from exams.models import StoryLecture
from exams.parsing import extract_json

BRIDGE_PATTERNS = [
    'jaise insaan',
    'insaani duniya',
    'insaanon ki tarah',
    'insaanon mein',
    'bilkul waise hi',
    'isi tarah',
]

EVENT_MARKERS = [
    # Conjunctions of sequence
    'phir', 'aur phir',
    'uske baad', 'us ke baad',
    'iske baad', 'is ke baad',
    'baad mein', 'baad me',
    'aakhir', 'aakhir mein',
    'agli', 'agle', 'agla',
    'doosre din', 'doosray din', 'doosri din',
    # Temporal anchors common in Roman Urdu narrative
    'jab', 'jab ke',
    'ek din', 'aik din',
    'subah', 'dopehar', 'shaam', 'raat',
    'raat ko', 'din mein',
]

# Turn 4e (2026-10-11) - V2, V6, V7 additions.
# Standards: Tobler et al. 2025 (narrative structure); Clement 1993
#   (bridging analogies); Rule 8 (no Urdu script); AERA 2014 Std 1.0.
REQUIRED_BEATS = ("hook", "analogy", "bridge", "concept", "return")
MIN_PARAGRAPHS = 4
KC_REF_RE = re.compile(r"\bC9-[A-Z]{2}\d{2}-[A-Z0-9_]+")

_URDU_RANGES = [(0x0600, 0x06FF), (0x0750, 0x077F),
                (0xFB50, 0xFDFF), (0xFE70, 0xFEFF)]
URDU_RE = re.compile(
    "[" + "".join(chr(lo) + "-" + chr(hi) for lo, hi in _URDU_RANGES) + "]"
)


def _has_urdu_script(s):
    return bool(URDU_RE.search(str(s or "")))


def _count_paragraphs(text):
    parts = [p.strip() for p in text.split("\n\n") if p.strip()]
    if len(parts) >= 2:
        return len(parts)
    return len(re.findall(r"[.!?]", text))


def validate_story(text, beats=None):
    errors = []
    if not text:
        errors.append('empty')
        return errors

    # V1 - word count
    wc = len(text.split())
    if wc < 250:
        errors.append('V1 too short ' + str(wc))
    if wc > 400:
        errors.append('V1 too long ' + str(wc))

    # V2 - five beats
    if isinstance(beats, dict):
        missing = [b for b in REQUIRED_BEATS
                   if not str(beats.get(b) or "").strip()]
        if missing:
            errors.append('V2 missing beats: ' + ",".join(missing))
    else:
        if _count_paragraphs(text) < MIN_PARAGRAPHS:
            errors.append('V2 beats not separable')

    low = text.lower()
    # V3 - bridge
    if not any(p in low for p in BRIDGE_PATTERNS):
        errors.append('V3 no bridge phrase')

    # V4 - named character
    if not re.search(r"\b[A-Z][a-z]{2,}\b", text):
        errors.append('V4 no named character')

    # V5 - event markers
    if sum(1 for m in EVENT_MARKERS if m in low) < 2:
        errors.append('V5 too few event markers')

    # V6 - KC ref near end
    if not KC_REF_RE.search(text[-200:]):
        errors.append('V6 no KC reference near end')

    # V7 - no Urdu script
    if _has_urdu_script(text):
        errors.append('V7 Urdu script present (Rule 8)')

    return errors


class Command(BaseCommand):
    help = "Ingest story-lectures JSON. Creates StoryLecture rows."

    def add_arguments(self, parser):
        parser.add_argument("json_file", type=str)
        parser.add_argument("--strict", action="store_true",
                            help="Reject stories that fail validation.")

    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 e:
            raise CommandError("Invalid JSON: " + str(e))

        teaching_date = self._parse_date(data.get("teaching_date"))
        source_exam_date = self._parse_date(data.get("source_exam_date"))
        subjects = data.get("subjects") or []
        if not subjects:
            raise CommandError("No subjects in input.")

        created = 0
        updated = 0
        warnings = 0
        with transaction.atomic():
            for sub in subjects:
                subject = (sub.get("subject") or "").strip()
                chapter = (sub.get("chapter") or "").strip()
                if not subject:
                    continue
                for s in sub.get("stories") or []:
                    qi = int(s.get("question_index") or 0)
                    qt = (s.get("question_text") or "").strip()
                    story = (s.get("story_text") or "").strip()
                    comp = (s.get("comprehension_question") or "").strip()
                    analogy = (s.get("analogy_used") or "").strip()
                    if not (qi and qt and story and comp):
                        self.stderr.write("skip incomplete " + subject)
                        warnings += 1
                        continue
                    errs = validate_story(story, beats=s.get("beats"))
                    if errs:
                        self.stderr.write("WARN " + subject + " Q" + str(qi) + ": " + "; ".join(errs))
                        warnings += 1
                        if strict:
                            continue
                    obj, is_new = StoryLecture.objects.update_or_create(
                        subject=subject, question_index=qi, teaching_date=teaching_date,
                        defaults={
                            "chapter": chapter,
                            "question_text": qt,
                            "story_text": story,
                            "analogy_used": analogy,
                            "comprehension_question": comp,
                            "source_exam_date": source_exam_date,
                        },
                    )
                    if is_new:
                        created += 1
                    else:
                        updated += 1
                    tag = "new" if is_new else "updated"
                    self.stdout.write("  " + subject + " Q" + str(qi) + " - " + tag)

        self.stdout.write(self.style.SUCCESS(
            "Created: " + str(created) + ", Updated: " + str(updated) + ", Warnings: " + str(warnings)))

    def _parse_date(self, s):
        if isinstance(s, date):
            return s
        try:
            return date.fromisoformat(s)
        except (ValueError, TypeError):
            raise CommandError("Invalid date: " + str(s))
