"""Story generator — rule-based template filler with subject archetypes.

Fixes over v2:
- Gender-aware archetypes (Urdu verb agreement)
- Expanded blocklist: singular + plural, case-insensitive
- Misconception text sanitized (meta-referential 'students' replaced)
- Spacing guard: post-process to fix missing spaces
"""
import re
from ._archetypes import get_archetype

HARD_BLOCK_WORDS = {
    'student', 'students', 'learner', 'learners',
    'misconception', 'misconceptions',
    'task', 'tasks', 'item', 'items',
}

TITLE_CLEANUP_PATTERNS = [
    r'\s*\(all tiers\)\s*',
    r'\s*\(.*?\)\s*',
    r'\s*glossary\s*',
]

TOKEN_RE = re.compile(r'[a-zA-Z]+')

# Common concatenation artifacts to fix
SPACING_FIXES = [
    (r'\bsochraha\b', 'soch raha'),
    (r'\bsochrahi\b', 'soch rahi'),
    (r'\bkarraha\b', 'kar raha'),
    (r'\bkarrahi\b', 'kar rahi'),
    (r'\baikhi\b', 'aik hi'),
    (r'\bsochpar\b', 'soch par'),
    (r'\baurneechay\b', 'aur neechay'),
]


def _clean_title(title):
    if not title:
        return 'is concept'
    t = title
    for pat in TITLE_CLEANUP_PATTERNS:
        t = re.sub(pat, ' ', t, flags=re.IGNORECASE)
    t = t.strip()
    return t or 'is concept'


def _has_block_word(text):
    tokens = set(TOKEN_RE.findall((text or '').lower()))
    return bool(tokens & HARD_BLOCK_WORDS)


def _sanitize_mechanism(mech):
    if not mech:
        return ''
    sentences = re.split(r'(?<=[.!?])\s+', mech.strip())
    kept = []
    for s in sentences:
        if _has_block_word(s):
            continue
        if s.strip():
            kept.append(s.strip().rstrip('.'))
    return '. '.join(kept) if kept else ''


def _sanitize_misconception(text):
    """Replace meta-referential words with story-safe alternatives."""
    if not text:
        return ''
    t = text.strip()
    t = re.sub(r'\bstudents\b', 'log', t, flags=re.IGNORECASE)
    t = re.sub(r'\bstudent\b', 'aadmi', t, flags=re.IGNORECASE)
    t = re.sub(r'\blearners\b', 'log', t, flags=re.IGNORECASE)
    t = re.sub(r'\blearner\b', 'aadmi', t, flags=re.IGNORECASE)
    return t


def _select_key_terms(kc, misconception_text, mechanism_text, n=2):
    if not isinstance(kc.key_terms, list):
        return []
    target = f"{misconception_text or ''} {mechanism_text or ''}".lower()
    target_tokens = set(TOKEN_RE.findall(target))
    scored = []
    for t in kc.key_terms:
        if not isinstance(t, dict):
            continue
        term = (t.get('term') or '').strip()
        if not term:
            continue
        term_tokens = set(TOKEN_RE.findall(term.lower()))
        overlap = len(term_tokens & target_tokens)
        scored.append((overlap, term))
    scored.sort(key=lambda x: -x[0])
    return [t for _, t in scored[:n]]


def can_generate(kc):
    if not isinstance(kc.misconceptions, list) or len(kc.misconceptions) == 0:
        return False, 'no_misconceptions'
    if not isinstance(kc.key_terms, list) or len(kc.key_terms) == 0:
        return False, 'no_key_terms'
    m = kc.misconceptions[0]
    if not isinstance(m, dict):
        return False, 'misconception_not_dict'
    if not (m.get('text') or '').strip():
        return False, 'misconception_text_empty'
    if not (m.get('mechanism') or '').strip():
        return False, 'misconception_mechanism_empty'
    return True, None


def generate_draft(kc):
    ok, reason = can_generate(kc)
    if not ok:
        return None, reason

    m = kc.misconceptions[0]
    misconception_raw = m['text'].strip().rstrip('.')
    misconception_clean = _sanitize_misconception(misconception_raw)
    mechanism_raw = m['mechanism'].strip().rstrip('.')
    mechanism_clean = _sanitize_mechanism(mechanism_raw)
    terms = _select_key_terms(kc, misconception_clean, mechanism_raw, n=2)
    title = _clean_title(kc.title or kc.code or '')

    archetype = get_archetype(kc.subject or 'General', seed=kc.code)
    draft = archetype.render(
        title=title,
        misconception=misconception_clean,
        mechanism=mechanism_clean,
        terms=terms,
    )

    # Post-process: fix common concatenation artifacts
    for pat, repl in SPACING_FIXES:
        draft = re.sub(pat, repl, draft)

    # Final guard: no double spaces, no space before punctuation
    draft = re.sub(r'\s+', ' ', draft).strip()

    return draft, None
