"""Audit the lecture decks against the checks a screen reader depends on.

Four checks run. Alt text on every picture, which PowerPoint stores on the
picture's cNvPr element. A title on every slide, since a screen reader reads
the title to announce where the reader has landed and PowerPoint's own outline
and accessibility checker both read the same placeholder. A header row flag on
every table, which names the column for each cell beneath it. A title in the
file properties, which names the deck in a reader's list.

usage: python pptx_a11y.py <decks_dir>
"""
import re
import sys
import zipfile
from pathlib import Path

from lxml import etree

P = "http://schemas.openxmlformats.org/presentationml/2006/main"
A = "http://schemas.openxmlformats.org/drawingml/2006/main"
DC = "http://purl.org/dc/elements/1.1/"
SLIDE = re.compile(r"ppt/slides/slide(\d+)\.xml$")


def audit(path: Path):
    z = zipfile.ZipFile(path)
    slides = sorted((n for n in z.namelist() if SLIDE.search(n)),
                    key=lambda n: int(SLIDE.search(n).group(1)))
    pics = noalt = untitled = tables = nohdr = 0
    for n in slides:
        root = etree.fromstring(z.read(n))
        for pic in root.iter(f"{{{P}}}pic"):
            pics += 1
            nv = pic.find(f".//{{{P}}}cNvPr")
            if nv is None or not (nv.get("descr") or "").strip():
                noalt += 1
        titled = False
        for sp in root.iter(f"{{{P}}}sp"):
            ph = sp.find(f".//{{{P}}}ph")
            if ph is not None and ph.get("type") in ("title", "ctrTitle"):
                txt = "".join(t.text or "" for t in sp.iter(f"{{{A}}}t"))
                if txt.strip():
                    titled = True
        if not titled:
            untitled += 1
        for tbl in root.iter(f"{{{A}}}tbl"):
            tables += 1
            pr = tbl.find(f"{{{A}}}tblPr")
            if pr is None or pr.get("firstRow") not in ("1", "true"):
                nohdr += 1
    try:
        core = etree.fromstring(z.read("docProps/core.xml"))
        title = (core.findtext(f"{{{DC}}}title") or "").strip()
    except KeyError:
        title = ""
    return {"slides": len(slides), "pictures": pics, "no alt": noalt,
            "untitled slides": untitled, "tables": tables,
            "tables without a header row": nohdr,
            "no file title": 0 if title else 1}


def main():
    src = Path(sys.argv[1])
    total = {}
    for f in sorted(src.glob("*.pptx")):
        r = audit(f)
        flags = r["no alt"] + r["untitled slides"] + \
            r["tables without a header row"] + r["no file title"]
        print(f"  {'FAIL' if flags else 'ok  '} {f.name[:56]:58} "
              f"slides {r['slides']:3d}  pics {r['pictures']:3d}  "
              f"noalt {r['no alt']:2d}  untitled {r['untitled slides']:2d}  "
              f"tbl {r['tables']:2d}/{r['tables without a header row']:2d}  "
              f"title {'set' if not r['no file title'] else 'NOT SET'}")
        for k, v in r.items():
            total[k] = total.get(k, 0) + v
    print()
    for k, v in total.items():
        print(f"  {k:32} {v}")
    bad = (total.get("no alt", 0) + total.get("untitled slides", 0)
           + total.get("tables without a header row", 0)
           + total.get("no file title", 0))
    print(f"\ntotal findings: {bad}")
    return 1 if bad else 0


if __name__ == "__main__":
    sys.exit(main())
