"""Give every deck slide a title a screen reader can announce.

The decks draw their headings as free text boxes on a blank layout, so no
slide carries a title placeholder. PowerPoint's accessibility checker reports
a missing title on all 1,177 slides, and a screen reader announces the slide
number and nothing else.

Each slide gets a title placeholder holding the heading already on the slide,
positioned off the canvas so the visible design does not change. Microsoft
documents that placement for exactly this case. The heading comes from the
slide itself: the largest type in the upper region, falling back to the
figure's own name on a slide that carries only a figure and its source note,
and to the section label on a transition slide whose body runs long.

    python deck_titles.py <decks_dir> <out_dir> [--check]

--check reports what each title would be and writes nothing.
"""
import io
import re
import shutil
import sys
import zipfile
from datetime import datetime
from pathlib import Path

from lxml import etree

P = "http://schemas.openxmlformats.org/presentationml/2006/main"
A = "http://schemas.openxmlformats.org/drawingml/2006/main"
SLIDE = re.compile(r"ppt/slides/slide(\d+)\.xml$")
EYEBROW = re.compile(r"^(CHAPTER \d+|PART [IVX]+|\d+)$", re.I)
FOOTER = re.compile(r"Geospatial Artificial Intelligence Risks\s*\|")
FIGNAME = re.compile(r"Figure (\d+\.\d+)[,.]?\s*[“\"](.+?)[”\"]")
CAP = 95


def shapes(root):
    """Text shapes with their vertical position and largest type size."""
    out = []
    for sp in root.iter(f"{{{P}}}sp"):
        txt = " ".join(t.text or "" for t in sp.iter(f"{{{A}}}t"))
        txt = re.sub(r"\s+", " ", txt).strip()
        if not txt or FOOTER.search(txt) or EYEBROW.match(txt):
            continue
        off = sp.find(f".//{{{A}}}off")
        y = int(off.get("y")) if off is not None else 0
        sizes = [int(r.get("sz")) for r in sp.iter(f"{{{A}}}rPr")
                 if r.get("sz")]
        out.append((y, max(sizes) if sizes else 0, txt))
    return out


def title_for(root):
    sh = shapes(root)
    if not sh:
        return "Section divider"
    short = [s for s in sh if len(s[2]) <= CAP]
    if short:
        top = sorted(short, key=lambda s: s[0])[:4]
        return max(top, key=lambda s: s[1])[2]
    for _, _, txt in sh:
        m = FIGNAME.search(txt)
        if m:
            return f"Figure {m.group(1)}. {m.group(2)}"
    txt = max(sh, key=lambda s: s[1])[2]
    cut = re.split(r"(?<=[.;:])\s", txt)[0]
    if len(cut) > CAP:
        cut = cut[:CAP].rsplit(" ", 1)[0] + "..."
    return cut


def title_sp(text, shape_id):
    """A title placeholder parked off the canvas, carrying the heading."""
    xml = f"""<p:sp xmlns:p="{P}" xmlns:a="{A}">
<p:nvSpPr><p:cNvPr id="{shape_id}" name="Title {shape_id}"/>
<p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr>
<p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>
<p:spPr><a:xfrm><a:off x="-9144000" y="0"/>
<a:ext cx="8229600" cy="609600"/></a:xfrm>
<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr>
<p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US"/>
<a:t>{text}</a:t></a:r></a:p></p:txBody></p:sp>"""
    return etree.fromstring(xml)


def next_id(root):
    ids = [int(e.get("id")) for e in root.iter(f"{{{P}}}cNvPr")
           if (e.get("id") or "").isdigit()]
    return max(ids) + 1 if ids else 2


def patch(path: Path, out: Path, check: bool):
    z = zipfile.ZipFile(path)
    names = z.namelist()
    data = {n: z.read(n) for n in names}
    added, titles = 0, []
    for n in sorted((x for x in names if SLIDE.search(x)),
                    key=lambda x: int(SLIDE.search(x).group(1))):
        root = etree.fromstring(data[n])
        spTree = root.find(f"{{{P}}}cSld/{{{P}}}spTree")
        if spTree is None:
            continue
        has = any(ph.get("type") in ("title", "ctrTitle")
                  for ph in root.iter(f"{{{P}}}ph"))
        text = title_for(root)
        titles.append((int(SLIDE.search(n).group(1)), text))
        if has or check:
            continue
        safe = (text.replace("&", "&amp;").replace("<", "&lt;")
                .replace(">", "&gt;"))
        # A screen reader walks the shapes in the order the file lists them,
        # so the title goes ahead of the drawn shapes and gets announced
        # first. The two group properties elements must stay at the front.
        at = 0
        for child in spTree:
            if etree.QName(child).localname in ("nvGrpSpPr", "grpSpPr"):
                at += 1
            else:
                break
        spTree.insert(at, title_sp(safe, next_id(root)))
        data[n] = etree.tostring(root, xml_declaration=True,
                                 encoding="UTF-8", standalone=True)
        added += 1

    if not check and added:
        # The core properties title names the deck in a reader's file list,
        # and PowerPoint's own checker reports it missing when unset.
        core = data.get("docProps/core.xml")
        if core is not None:
            croot = etree.fromstring(core)
            dc = "http://purl.org/dc/elements/1.1/"
            el = croot.find(f"{{{dc}}}title")
            if el is None:
                el = etree.SubElement(croot, f"{{{dc}}}title")
            el.text = titles[0][1] if titles else path.stem
            data["docProps/core.xml"] = etree.tostring(
                croot, xml_declaration=True, encoding="UTF-8",
                standalone=True)
        buf = io.BytesIO()
        with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zout:
            for n in names:
                zout.writestr(z.getinfo(n), data[n])
        out.write_bytes(buf.getvalue())
    return added, titles


def main():
    src, dst = Path(sys.argv[1]), Path(sys.argv[2])
    check = "--check" in sys.argv
    if not check:
        dst.mkdir(parents=True, exist_ok=True)
    stamp = datetime.now().strftime("%Y-%m-%d_%H%M") + "_TJB"
    total = 0
    for f in sorted(src.glob("*.pptx")):
        newname = re.sub(r"_\d{4}-\d{2}-\d{2}_\d{4}_TJB\.pptx$",
                         f"_{stamp}.pptx", f.name)
        if newname == f.name:
            newname = f"{f.stem}_{stamp}.pptx"
        added, titles = patch(f, dst / newname, check)
        total += added
        print(f"  {f.name[:50]:52} slides {len(titles):4d}  "
              f"titles added {added:4d}")
        if check:
            for num, t in titles[:3]:
                print(f"      slide {num:3d}  {t[:72]}")
    print(f"\ntitle placeholders added: {total}")
    if not check:
        print(f"decks written to {dst}")
    return 0


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