"""Count stored main-document comments, resolution markers and body references locally."""
import argparse
from collections import Counter
from pathlib import PurePosixPath
from posixpath import dirname, join, normpath
from xml.etree import ElementTree as ET
from zipfile import BadZipFile, ZipFile

W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
W14 = "http://schemas.microsoft.com/office/word/2010/wordml"
W15 = "http://schemas.microsoft.com/office/word/2012/wordml"


def target(archive, source, kind):
    p = PurePosixPath(source)
    rels = str(p.parent / "_rels" / (p.name + ".rels")) if source else "_rels/.rels"
    if rels not in archive.namelist():
        return None
    for rel in ET.fromstring(archive.read(rels)):
        if rel.get("Type", "").rsplit("/", 1)[-1] == kind and rel.get("TargetMode") != "External":
            path = rel.get("Target", "")
            return normpath(path.lstrip("/") if path.startswith("/") else join(dirname(source), path))
    return None


def summarize(archive):
    doc = target(archive, "", "officeDocument")
    if not doc:
        raise ValueError("The file does not identify a main Office document.")
    body = ET.fromstring(archive.read(doc))
    if body.tag != f"{{{W}}}document":
        raise ValueError("Expected a standard WordprocessingML main document.")
    anchors = {r.get(f"{{{W}}}id") for r in body.iter(f"{{{W}}}commentReference")}
    comments = target(archive, doc, "comments")
    extended = target(archive, doc, "commentsExtended")
    flags = {}
    if extended:
        for rec in ET.fromstring(archive.read(extended)).iter(f"{{{W15}}}commentEx"):
            flags[rec.get(f"{{{W15}}}paraId")] = rec.get(f"{{{W15}}}done", "0")
    result = Counter()
    if comments:
        for comment in ET.fromstring(archive.read(comments)).iter(f"{{{W}}}comment"):
            paragraphs = list(comment.iter(f"{{{W}}}p"))
            key = paragraphs[-1].get(f"{{{W14}}}paraId") if paragraphs else None
            flag = flags.get(key) if key is not None else None
            state = {"0": "open", "false": "open", "off": "open", "1": "resolved",
                     "true": "resolved", "on": "resolved"}.get(flag, "status unavailable")
            result[state] += 1
            result["stored comments"] += 1
            result["with main-body reference"] += int(comment.get(f"{{{W}}}id") in anchors)
    return result


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("docx", help="Path to your local .docx")
    args = parser.parse_args()
    try:
        with ZipFile(args.docx) as docx:
            counts = summarize(docx)
    except (OSError, BadZipFile, ET.ParseError, ValueError, KeyError) as error:
        parser.exit(1, f"Could not read this DOCX: {error}\n")
    for key in ("stored comments", "open", "resolved", "status unavailable", "with main-body reference"):
        print(f"{key}: {counts[key]}")
