"""Read actual DOCX bookmarks without editing or inventing template metadata."""
import argparse
import hashlib
import json
from pathlib import Path
from xml.etree import ElementTree as ET
from zipfile import ZipFile

W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"


def inspect_bookmarks(path):
    source = Path(path)
    with ZipFile(source) as archive:
        entry = archive.getinfo("word/document.xml")
        if entry.file_size > 4 * 1024 * 1024:
            raise ValueError("document_xml_size_limit")
        root = ET.fromstring(archive.read(entry))
        active, records, names = {}, [], set()
        for node in root.iter():
            if node.tag == W + "bookmarkStart":
                identity, name = node.get(W + "id"), node.get(W + "name")
                if not identity or not name or identity in active or name in names:
                    raise ValueError("bookmark_identity_ambiguous")
                names.add(name)
                active[identity] = {"name": name, "parts": []}
            elif node.tag == W + "t":
                for record in active.values():
                    record["parts"].append(node.text or "")
            elif node.tag == W + "bookmarkEnd":
                record = active.pop(node.get(W + "id"), None)
                if record is None:
                    raise ValueError("bookmark_end_without_start")
                records.append({"name": record["name"], "text": "".join(record["parts"])})
        if active or not records:
            raise ValueError("bookmarks_incomplete_or_absent")
    return {"schemaVersion": "bf.e10.docx-bookmark-inspection.v1",
            "sourceSha256": hashlib.sha256(source.read_bytes()).hexdigest(),
            "sourceBytes": source.stat().st_size, "bookMarkList": records,
            "bookmarkCount": len(records), "nativeImportVerified": False}


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--input", required=True)
    parser.add_argument("--output", required=True)
    args = parser.parse_args()
    result = inspect_bookmarks(args.input)
    with Path(args.output).open("x", encoding="utf-8") as target:
        json.dump(result, target, ensure_ascii=False, indent=2)
        target.write("\n")
    print(json.dumps({"bookmarkCount": result["bookmarkCount"],
                      "sourceBytes": result["sourceBytes"], "writeToTenant": False}))
