#!/usr/bin/python3
"""Insert troff .so includes into Sphinx-built zshall.1 (before FILES)."""
import argparse
import sys
from pathlib import Path


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("zshall_man", type=Path, help="Path to build/man/zshall.1")
    parser.add_argument(
        "pages",
        nargs="+",
        help="Man page basenames to .so (e.g. zshroadmap zshmisc …)",
    )
    args = parser.parse_args()

    path = args.zshall_man
    if not path.is_file():
        print(f"error: missing {path}", file=sys.stderr)
        sys.exit(1)

    text = path.read_text(encoding="utf-8")
    if ".so man1/" in text:
        print(f"{path} already contains .so includes")
        return

    needle = ".SH FILES\n"
    if needle not in text:
        print(f"error: {needle!r} not found in {path}", file=sys.stderr)
        sys.exit(1)

    block = "".join(f".so man1/{name}.1\n" for name in args.pages)
    path.write_text(text.replace(needle, block + needle, 1), encoding="utf-8")
    print(f"Inserted {len(args.pages)} .so includes into {path}")


if __name__ == "__main__":
    main()
