"""Audit a Word file against the accessibility checks a reader depends on.

Five checks run. Alt text on every drawing, since a screen reader otherwise
announces an unnamed graphic. Heading styles rather than bold body text, which
is what lets a reader jump between sections. A marked header row on every
table, expressed as the tblHeader property, which makes a screen reader repeat
the column names on every row and makes Word repeat them across a page break.
A stated document language, which decides the voice a screen reader uses. A
title in the document properties, which names the file in a reader's list.

usage: python docx_a11y.py <file.docx> [more.docx ...]
"""
import sys
import zipfile
from pathlib import Path

from lxml import etree

W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
WP = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
CP = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"
DC = "http://purl.org/dc/elements/1.1/"


def audit(path: Path):
    z = zipfile.ZipFile(path)
    doc = etree.fromstring(z.read("word/document.xml"))
    out = []

    draw = list(doc.iter(f"{{{WP}}}docPr"))
    noalt = [d for d in draw if not (d.get("descr") or "").strip()]
    out.append((len(noalt), f"drawings {len(draw)}, without alt text "
                            f"{len(noalt)}"))

    # A heading reaches a screen reader either through a Heading style or
    # through an outline level set on the paragraph, and the workbook editions
    # use the second so the original's direct formatting survives.
    levels = []
    for p in doc.iter(f"{{{W}}}p"):
        pr = p.find(f"{{{W}}}pPr")
        if pr is None:
            continue
        ol = pr.find(f"{{{W}}}outlineLvl")
        if ol is not None and (ol.get(f"{{{W}}}val") or "").isdigit():
            levels.append(int(ol.get(f"{{{W}}}val")) + 1)
            continue
        st = pr.find(f"{{{W}}}pStyle")
        v = (st.get(f"{{{W}}}val") or "") if st is not None else ""
        if v.lower().startswith("heading") and v[7:].strip().isdigit():
            levels.append(int(v[7:].strip()))
    skips = sum(1 for a, b in zip(levels, levels[1:]) if b > a + 1)
    out.append((skips if levels else 1,
                f"headings {len(levels)}, level skips {skips}"))

    def bold_first_column(t, rows):
        """A label and value table carries its headers down the first column."""
        if max(len(r.findall(f"{{{W}}}tc")) for r in rows) != 2:
            return False
        for r in rows:
            tc = r.findall(f"{{{W}}}tc")
            if not tc or tc[0].find(f".//{{{W}}}b") is None:
                return False
        return True

    tables = list(doc.iter(f"{{{W}}}tbl"))
    unmarked, rowhdr = 0, 0
    for t in tables:
        rows = t.findall(f"{{{W}}}tr")
        if not rows:
            continue
        if rows[0].find(f"{{{W}}}trPr/{{{W}}}tblHeader") is not None:
            continue
        if bold_first_column(t, rows):
            rowhdr += 1
            continue
        unmarked += 1
    out.append((unmarked, f"tables {len(tables)}, header row not marked "
                          f"{unmarked}, row-header tables {rowhdr}"))

    try:
        st = etree.fromstring(z.read("word/styles.xml"))
        lang = st.find(f".//{{{W}}}docDefaults//{{{W}}}lang")
        has = lang is not None and (lang.get(f"{{{W}}}val") or "")
    except KeyError:
        has = ""
    out.append((0 if has else 1, f"document language {has or 'NOT SET'}"))

    try:
        core = etree.fromstring(z.read("docProps/core.xml"))
        title = (core.findtext(f"{{{DC}}}title") or "").strip()
    except KeyError:
        title = ""
    out.append((0 if title else 1, f"title property {title or 'NOT SET'}"))
    return out


def main():
    bad = 0
    for arg in sys.argv[1:]:
        p = Path(arg)
        print(f"\n{p.name}")
        for n, line in audit(p):
            print(f"  {'FAIL' if n else 'ok  '} {line}")
            bad += n
    print(f"\ntotal findings: {bad}")
    return 1 if bad else 0


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