"""Replace the cartridge's lab documents with freshly built ones.

The 21 September lab files carried no heading structure, no marked table
header rows and no document title, so a screen reader read each one as an
unbroken run of body paragraphs. build_lab_files.py rebuilds them from the
draft with all three corrected. This swaps them into the cartridge and
rewrites every reference to the old file name, in the manifest and in the
assignment pages alike.

Matching runs on the name with the build stamp removed, so a file pairs with
its replacement regardless of when either was built.

usage: python swap_imscc_labs.py <in.imscc> <new_labs_dir> <out.imscc>
"""
import io
import re
import sys
import zipfile
from pathlib import Path

STAMP = re.compile(r"_\d{4}-\d{2}-\d{2}_\d{4}_TJB(?=\.(?:docx|pptx)$)")


def key(name: str) -> str:
    return STAMP.sub("", Path(name).name)


def main():
    src, newdir, dst = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])
    fresh = {key(p.name): p for p in sorted(newdir.iterdir())
             if p.suffix.lower() in (".docx", ".pptx")}
    if not fresh:
        print(f"no .docx files in {newdir}")
        return 1

    zin = zipfile.ZipFile(src)
    swapped, renames, missing = 0, {}, []
    for info in zin.infolist():
        if not info.filename.lower().endswith((".docx", ".pptx")):
            continue
        k = key(info.filename)
        if k not in fresh:
            missing.append(info.filename)
            continue
        new_name = (Path(info.filename).parent
                    / fresh[k].name).as_posix()
        if new_name != info.filename:
            renames[Path(info.filename).name] = fresh[k].name
        swapped += 1
    for m in missing:
        print(f"  no replacement built for {Path(m).name[:66]}")

    buf = io.BytesIO()
    pages = 0
    with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zout:
        for info in zin.infolist():
            name, data = info.filename, zin.read(info.filename)
            if name.lower().endswith((".docx", ".pptx")):
                k = key(name)
                if k in fresh:
                    data = fresh[k].read_bytes()
                    name = (Path(name).parent / fresh[k].name).as_posix()
            elif name.lower().endswith((".xml", ".html", ".htm")):
                text = data.decode("utf-8")
                before = text
                for old, new in renames.items():
                    text = text.replace(old, new)
                    # A reference may carry the name URL-encoded, where a
                    # space or a comma in a file name became a percent escape.
                    text = text.replace(old.replace(" ", "%20"),
                                        new.replace(" ", "%20"))
                if text != before:
                    pages += 1
                    data = text.encode("utf-8")
            zout.writestr(info, data) if name == info.filename else \
                zout.writestr(name, data)
    dst.write_bytes(buf.getvalue())

    print(f"documents replaced     : {swapped}")
    print(f"file names changed     : {len(renames)}")
    print(f"files rewritten for the new names: {pages}")
    print(f"wrote {dst}  ({dst.stat().st_size / 1_048_576:.1f} MB)")

    # A reference left pointing at a replaced file would download nothing, so
    # the check runs on the written cartridge rather than on the plan.
    z = zipfile.ZipFile(dst)
    names = set(z.namelist())
    stale = 0
    for n in names:
        if not n.lower().endswith((".xml", ".html", ".htm")):
            continue
        txt = z.read(n).decode("utf-8", "replace")
        for old in renames:
            if old in txt:
                print(f"  STALE reference to {old[:50]} in {n}")
                stale += 1
    print(f"stale references: {stale}")
    return 1 if stale else 0


if __name__ == "__main__":
    sys.exit(main())
