"""Audit the built site against the WCAG 2.1 AA checks a static page can fail.

Seven checks run. Contrast ratio of every color pair the stylesheet declares,
against 4.5 to 1 for body text and 3 to 1 for large text and interface
borders. Heading order, which fails where a level skips on the way down.
A language attribute on the html element. Table markup, which needs a header
row expressed as th elements rather than styled td elements. Link text, read
with no surrounding sentence, since a screen reader lists links on their own.
An alt attribute on every img element. Title uniqueness across the pages.

usage: python site_a11y.py <site_dir>
"""
import re
import sys
from collections import Counter
from pathlib import Path

HEX = re.compile(r"#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b")
VAGUE = {"here", "click here", "this", "read more", "more", "link",
         "this page", "learn more", "download"}


def lum(hexcode):
    h = hexcode.lstrip("#")
    if len(h) == 3:
        h = "".join(c * 2 for c in h)
    parts = []
    for i in (0, 2, 4):
        c = int(h[i:i + 2], 16) / 255
        parts.append(c / 12.92 if c <= 0.03928
                     else ((c + 0.055) / 1.055) ** 2.4)
    r, g, b = parts
    return 0.2126 * r + 0.7152 * g + 0.0722 * b


def ratio(a, b):
    la, lb = lum(a), lum(b)
    hi, lo = max(la, lb), min(la, lb)
    return (hi + 0.05) / (lo + 0.05)


def css_pairs(css):
    """Every rule that sets a color, paired with the background in force."""
    page_bg = "#ffffff"
    m = re.search(r"body\s*\{[^}]*background(?:-color)?:\s*(#[0-9a-fA-F]{3,6})",
                  css)
    if m:
        page_bg = m.group(1)
    out = []
    for rule in re.finditer(r"([^{}]+)\{([^}]*)\}", css):
        sel, body = rule.group(1).strip(), rule.group(2)
        fg = re.search(r"(?<!-)\bcolor:\s*(#[0-9a-fA-F]{3,6})", body)
        bg = re.search(r"background(?:-color)?:\s*(#[0-9a-fA-F]{3,6})", body)
        if not fg:
            continue
        big = bool(re.search(r"\bh[1-3]\b", sel))
        out.append((sel, fg.group(1), (bg.group(1) if bg else page_bg), big))
    return out


def headings(html):
    return [(int(m.group(1)), re.sub(r"<[^>]+>", "", m.group(2)).strip()[:48])
            for m in re.finditer(r"<h([1-6])[^>]*>(.*?)</h\1>", html,
                                 re.S | re.I)]


def main():
    site = Path(sys.argv[1])
    css_text = "\n".join(p.read_text(encoding="utf-8")
                         for p in site.rglob("*.css"))
    print(f"stylesheets read: {len(list(site.rglob('*.css')))}")
    bad = 0
    for sel, fg, bg, big in css_pairs(css_text):
        r = ratio(fg, bg)
        need = 3.0 if big else 4.5
        if r < need:
            bad += 1
            print(f"  CONTRAST {r:4.2f} (needs {need}) {fg} on {bg}  {sel[:46]}")
    print(f"contrast failures: {bad}")

    pages = sorted(site.rglob("*.html"))
    titles, issues = Counter(), 0
    for p in pages:
        html = p.read_text(encoding="utf-8", errors="replace")
        rel = p.relative_to(site).as_posix()
        if not re.search(r"<html[^>]*\slang=", html, re.I):
            print(f"  LANG missing            {rel}")
            issues += 1
        hs = headings(html)
        if hs and hs[0][0] != 1:
            print(f"  H1 not first ({hs[0][0]})      {rel}")
            issues += 1
        if sum(1 for lv, _ in hs if lv == 1) > 1:
            print(f"  H1 repeated             {rel}")
            issues += 1
        prev = 0
        for lv, txt in hs:
            if prev and lv > prev + 1:
                print(f"  HEADING skip h{prev}->h{lv}    {rel}  {txt}")
                issues += 1
            prev = lv
        for m in re.finditer(r"<img\b[^>]*>", html, re.I):
            if not re.search(r"\salt=", m.group(0), re.I):
                print(f"  IMG no alt              {rel}")
                issues += 1
        for m in re.finditer(r"<table\b.*?</table>", html, re.S | re.I):
            if "<th" not in m.group(0).lower():
                print(f"  TABLE no th             {rel}")
                issues += 1
        for m in re.finditer(r"<a\b[^>]*>(.*?)</a>", html, re.S | re.I):
            txt = re.sub(r"<[^>]+>", " ", m.group(1))
            txt = re.sub(r"\s+", " ", txt).strip().lower().rstrip(".")
            if txt in VAGUE:
                print(f"  LINK text vague         {rel}  \"{txt}\"")
                issues += 1
            if not txt and "aria-label" not in m.group(0).lower():
                print(f"  LINK empty              {rel}")
                issues += 1
        t = re.search(r"<title>(.*?)</title>", html, re.S | re.I)
        titles[t.group(1).strip() if t else "(none)"] += 1
    for t, n in titles.items():
        if n > 1 or t == "(none)":
            print(f"  TITLE repeated {n:3d}x     {t[:52]}")
            issues += 1
    print(f"pages read: {len(pages)}")
    print(f"markup findings: {issues}")
    print(f"TOTAL: {bad + issues}")


if __name__ == "__main__":
    main()
