"""Reading-level estimation via Flesch-Kincaid (zero dependencies)."""

import re
from pathlib import Path


def check_readability(text) -> dict:
    """Compute Flesch-Kincaid Grade Level and Reading Ease for prose.

    Pure Python with a syllable-count heuristic; no NLP dependency.
    Maps to WCAG 2.1 Success Criterion 3.1.5 (Reading Level, AAA).

    ``text`` may be a string, a list of strings, or a path to a ``.md``,
    ``.qmd``, ``.Rmd``, or ``.txt`` file.

    Returns a dict with keys ``sentences``, ``words``, ``syllables``,
    ``flesch_kincaid_grade``, ``flesch_reading_ease``.
    """
    if isinstance(text, (list, tuple)):
        text = " ".join(text)
    if isinstance(text, Path):
        text = text.read_text(encoding="utf-8")
    elif isinstance(text, str) and text and len(text) < 260:
        try:
            p = Path(text)
            if p.is_file():
                text = p.read_text(encoding="utf-8")
        except OSError:
            pass
    text = re.sub(r"```[\s\S]*?```", " ", text or "")
    text = re.sub(r"`[^`]*`", " ", text)
    text = re.sub(r"[#*_>~\[\]()]", " ", text)

    sentences = _split_sentences(text)
    words     = _split_words(text)
    syllables = sum(_syllable_count(w) for w in words)

    n_s, n_w = len(sentences), len(words)
    if n_s == 0 or n_w == 0:
        return {"sentences": n_s, "words": n_w, "syllables": syllables,
                "flesch_kincaid_grade": None, "flesch_reading_ease": None}

    asl = n_w / n_s
    asw = syllables / n_w
    fk_grade = 0.39 * asl + 11.8 * asw - 15.59
    fk_ease  = 206.835 - 1.015 * asl - 84.6 * asw

    return {
        "sentences":            n_s,
        "words":                n_w,
        "syllables":            syllables,
        "flesch_kincaid_grade": round(fk_grade, 2),
        "flesch_reading_ease":  round(fk_ease, 2),
    }


def _split_sentences(text):
    parts = re.split(r"(?<=[.!?])\s+", text)
    return [s for s in parts if s.strip()]


def _split_words(text):
    return [w.lower() for w in re.findall(r"[A-Za-z']+", text)]


def _syllable_count(word):
    if not word:
        return 0
    word = word.lower()
    if len(word) > 2 and word.endswith("e") and not word.endswith("le"):
        word = word[:-1]
    groups = re.findall(r"[aeiouy]+", word)
    return max(1, len(groups))
