"""Expert 3 — Simplicity.

Grade-level vocabulary and sentence length.
Source: LREC 2026 evaluation framework.

Class 9 thresholds:
  - avg words per sentence <= 18
  - complex-word ratio (>= 4 syllables) <= 15%

Scoring:
  1.0  both pass
  0.5  one fails
  0.0  both fail
"""
import re

SENTENCE_SPLIT = re.compile(r'[.!?]+')
WORD_RE = re.compile(r'[a-zA-Z\u0600-\u06ff]+')
MAX_AVG_WORDS = 18
MAX_COMPLEX_RATIO = 0.15


def _syllable_estimate(word):
    word = word.lower()
    vowels = set('aeiou')
    count = 0
    prev_vowel = False
    for ch in word:
        is_v = ch in vowels
        if is_v and not prev_vowel:
            count += 1
        prev_vowel = is_v
    return max(1, count)


def evaluate(kc, story_text):
    if not story_text:
        return 0.0

    sentences = [s.strip() for s in SENTENCE_SPLIT.split(story_text) if s.strip()]
    words = WORD_RE.findall(story_text)
    if not sentences or not words:
        return 0.0

    avg_words = len(words) / len(sentences)
    sentence_ok = avg_words <= MAX_AVG_WORDS

    complex_count = sum(1 for w in words if _syllable_estimate(w) >= 4)
    complex_ratio = complex_count / len(words)
    vocab_ok = complex_ratio <= MAX_COMPLEX_RATIO

    if sentence_ok and vocab_ok:
        return 1.0
    if sentence_ok or vocab_ok:
        return 0.5
    return 0.0
