"""glossary_extract — derive a candidate glossary word list from the
real Chemistry corpus (ModelQuestions + KnowledgeComponent.key_terms).

Usage:
    python manage.py glossary_extract [--subject Chemistry] [--top N]
                                      [--min-freq F] [--out FILE]

Output JSON:
    {
      "subject": "Chemistry",
      "generated_at": "...",
      "top_n": 300,
      "min_freq": 2,
      "words": [
        {"word": "atom", "frequency": 45, "first_chapter": "Chapter 2",
         "sample": "atom ke nucleus mein ..."}
      ]
    }

Standards:
  Nation 2001 (corpus-driven high-frequency selection);
  Coxhead 2000 (data-derived academic/technical word list);
  Gagne 1971 (order by first curriculum appearance);
  ISO 8000 (data must be derived, not invented);
  AERA/APA/NCME 2014 Std 13.7 (each stored value is traceable);
  Rule 10 (single canonical extractor).
"""
import json
import re
from collections import Counter, defaultdict
from datetime import datetime, timezone
from pathlib import Path as _Path

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

from exams.models import KnowledgeComponent, ModelQuestion


TOKEN_RE = re.compile(r"[A-Za-z][A-Za-z\-]{2,}")

# Common stopwords + very-basic Tier-1 words a 9th-class student will know.
# The selection task is to find words they might NOT know.
# English stopwords (function words + very-basic Tier-1)
STOPWORDS = set("""
the and for with from into onto out off over under between among during
that this these those there here what which whose where when why how
not but also only just very more most much many some any each every all
one two three four five six seven eight nine ten
has have had having been being is are was were will would shall should
can could may might must do does did doing done
of in on at by to up as or if then than so such no yes
its it its their his her they them we our you your i me my he she
about above across after against along around before behind below
beneath beside beyond down near past since through toward upon within
without because while although though whether either neither
give write write gives writes wrote written given
question answer define state name list show tell
types type kind kinds form forms
""".split())

# Roman Urdu function words — Tier 1 for Pakistani students, skip them all
# Roman Urdu function words — comprehensive blacklist (Tier 1 for students)
ROMAN_URDU_BLACKLIST = set("""liye karne kisi jata wala kyunke hone hissa
karta karti karte karo kare karen kar
hota hoti hote hoti
jata jati jate jaye jayein jayega jayegi jayenge
wala wali wale walay
hona hone hoi hoga hogi honge
karna karne karke karta karti karte
liya liye liyi liya
banta banti bante banay banaya banai banao banaye
hissa hisson hissay
kyun kya kyunki kyunke kaun kis kisi
jab tab kab
yahan wahan kahan
yeh ye woh wo
is us in un ise use inhe unhe iska uski uske
bhi hi to na ni
raha rahi rahe rahay
sakte sakta sakti sako sakay
dega degi denge
laga lagi lage lagay
rakh rakhta rakhti rakhte
ata ati ate atay
gaya gayi gaye gayay
deta deti dete
leta leti lete
keemiyai kimiya
yehi wohi
jaisa jaisi jaise
matlab misaal misalen
zyada kam bahut thora
ek do teen char paanch chhe saat aath nau das
hain hai hoon hun the tha thi thay
mein hum tum aap
ka ki ke ko se ne par pr
aur ya lekin magar phir
agar warna
bas sirf
bana banai
sirf
jaise
lie
hua hui hue hona
jabhi tabhi
na to
hi
""".split())

STOPWORDS = STOPWORDS | ROMAN_URDU_BLACKLIST

# Common Roman-Urdu suffixes. If a word ends in one of these and is short,
# it is almost certainly Roman Urdu, not an English technical term.
RU_SUFFIXES_SHORT = (
    "iye", "ye", "ne", "ni", "ta", "te", "ti", "ya", "ay",
    "on", "en", "in", "ke", "ki", "ka", "ko", "se",
    "la", "le", "li", "wa", "we", "wi",
)

def is_englishish(w):
    # Step 1: reject Roman Urdu bigrams
    RU_DIGRAPHS = ("kh","gh","chh","jh","dh","rh","bh","ph","th","sh","ng",
                   "aa","ee","ii","oo","uu","ai","au")
    if any(d in w for d in RU_DIGRAPHS):
        return False
    # Step 2: reject short words ending in Roman Urdu suffixes
    if len(w) <= 6 and w.endswith(RU_SUFFIXES_SHORT):
        return False
    # Step 3: reject words with too many vowels
    vowels = sum(1 for c in w if c in "aeiou")
    if vowels < 2 or vowels > len(w) * 0.7:
        return False
    # Step 4: require at least one consonant cluster (English pattern)
    # Roman Urdu mostly alternates CV-CV-CV; English science words often
    # have consonant clusters (str-, -nd-, -ct-, -pt-, -rm-, -mp-, ...)
    has_cluster = False
    for i in range(len(w) - 1):
        if w[i] not in "aeiou" and w[i+1] not in "aeiou":
            has_cluster = True
            break
    # allow common exceptions
    exceptions = {"atom","acid","base","salt","bond","heat","mass","gas","ion","water","air"}
    if not has_cluster and w not in exceptions:
        return False
    return True
# Only keep tokens that look like English technical words. English
# science words have no Roman-Urdu patterns like 'aa', 'ee', 'oo', 'kh',
# 'gh', 'chh', 'th', 'ph' at word boundaries. Simplest reliable filter:
# require at least one of the "English-only" vowels/consonant clusters
# and forbid common Roman-Urdu digraphs.
ROMAN_URDU_DIGRAPHS = (
    "kh", "gh", "chh", "jh", "dh", "rh", "bh", "ph", "th", "sh", "ng",
    "aa", "ee", "ii", "oo", "uu", "ai", "au", "ay",
)



# Words we already know a student in Chemistry 9 will meet in daily life.
KNOWN_WORDS = set("""
air water fire earth salt sugar milk bread
plant animal food hand head body home school book
small large big short long hot cold warm cool
good bad new old hard soft fast slow
make made take taken keep kept
""".split())


class Command(BaseCommand):
    help = "Extract a candidate glossary word list from the Chemistry corpus."

    def add_arguments(self, parser):
        parser.add_argument("--subject", default="Chemistry")
        parser.add_argument("--top", type=int, default=300)
        parser.add_argument("--min-freq", type=int, default=2)
        parser.add_argument("--out", default="/tmp/glossary_candidates.json")

    def handle(self, *args, **opts):
        subj = opts["subject"]

        # -------- gather corpus --------
        questions = list(ModelQuestion.objects.filter(paper__subject=subj))
        kcs = list(KnowledgeComponent.objects.filter(subject=subj))

        # chapter-by-chapter, because we want "first chapter a word appears"
        chapter_of_q = {}
        for q in questions:
            # ModelQuestion has its own chapter field, may be blank; fall back to KC's chapter
            ch = (q.chapter or "").strip()
            if not ch and q.kc_code:
                kc = next((k for k in kcs if k.code == q.kc_code), None)
                if kc:
                    ch = kc.chapter or ""
            chapter_of_q[q.id] = ch or "(unknown)"

        # -------- count words --------
        freq = Counter()
        first_chapter = {}
        sample = {}
        for q in questions:
            text = " ".join([q.question_text or "", q.model_answer or ""])
            ch = chapter_of_q[q.id]
            for tok in TOKEN_RE.findall(text):
                w = tok.lower()
                if len(w) < 4:
                    continue
                if w in STOPWORDS or w in KNOWN_WORDS:
                    continue
                if not is_englishish(w):
                    continue
                freq[w] += 1
                if w not in first_chapter or ch < first_chapter[w]:
                    first_chapter[w] = ch
                if w not in sample:
                    sample[w] = (q.question_text or "")[:80]

        # also pull words from key_terms across KCs
        for kc in kcs:
            ch = kc.chapter or "(unknown)"
            for t in (kc.key_terms or []):
                for field in ("term", "roman_urdu", "definition", "example", "non_example"):
                    txt = t.get(field) or ""
                    for tok in TOKEN_RE.findall(txt):
                        w = tok.lower()
                        if len(w) < 4:
                            continue
                        if w in STOPWORDS or w in KNOWN_WORDS:
                            continue
                        if not is_englishish(w):
                            continue
                        freq[w] += 1
                        if w not in first_chapter or ch < first_chapter[w]:
                            first_chapter[w] = ch
                        if w not in sample:
                            sample[w] = (t.get("term") or "")[:80]

        # -------- rank --------
        # 1. filter by min frequency
        candidates = [(w, n) for w, n in freq.items() if n >= opts["min_freq"]]

        # 2. sort by (first_chapter, -frequency) — curriculum order first
        def chapter_key(ch):
            m = re.search(r"(\d+)", ch or "")
            return int(m.group(1)) if m else 999

        candidates.sort(key=lambda x: (chapter_key(first_chapter.get(x[0], "(unknown)")),
                                       -x[1], x[0]))

        top = candidates[:opts["top"]]

        words = [
            {"word": w, "frequency": n,
             "first_chapter": first_chapter.get(w, "(unknown)"),
             "sample": sample.get(w, "")}
            for w, n in top
        ]

        out = {
            "subject": subj,
            "generated_at": datetime.now(timezone.utc).isoformat(),
            "top_n": opts["top"],
            "min_freq": opts["min_freq"],
            "corpus": {
                "questions": len(questions),
                "kcs": len(kcs),
                "distinct_words": len(freq),
            },
            "words": words,
        }

        path = _Path(opts["out"])
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(json.dumps(out, indent=2, ensure_ascii=False), encoding="utf-8")
        self.stdout.write(f"wrote {path} ({path.stat().st_size} bytes)")
        self.stdout.write(
            f"corpus: {len(questions)} questions, {len(kcs)} KCs, "
            f"{len(freq)} distinct words. Kept top {len(words)}."
        )
        # Preview first 10
        for w in words[:10]:
            self.stdout.write(f"  {w['first_chapter']:12s} freq={w['frequency']:3d}  {w['word']}")
