"""只读检查常见插入删除修订及传统批注；不覆盖全部Word扩展。"""
import json
from pathlib import Path
import sys
from zipfile import ZipFile
import xml.etree.ElementTree as ET

NS = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
W = '{' + NS['w'] + '}'


def inspect(path):
    with ZipFile(path) as package:
        document = ET.fromstring(package.read('word/document.xml'))
        comments = ET.fromstring(package.read('word/comments.xml')) if 'word/comments.xml' in package.namelist() else None
        rows = []
        for kind in ('ins', 'del'):
            for node in document.findall('.//w:' + kind, NS):
                text = ''.join(node.itertext())
                rows.append({'类型': kind, '编号': node.get(W+'id'),
                             '作者': node.get(W+'author'), '时间': node.get(W+'date'), '文字': text})
        annotations = []
        if comments is not None:
            for node in comments.findall('w:comment', NS):
                annotations.append({'编号': node.get(W+'id'), '作者': node.get(W+'author'),
                                    '时间': node.get(W+'date'), '文字': ''.join(node.itertext())})
        anchors = {kind: [n.get(W+'id') for n in document.findall('.//w:'+kind, NS)]
                   for kind in ('commentRangeStart', 'commentRangeEnd', 'commentReference')}
        return {'文件': str(path), '修订': rows, '批注': annotations, '锚点': anchors}


if __name__ == '__main__':
    target = Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).with_name('n032-review-metadata.docx')
    print(json.dumps(inspect(target), ensure_ascii=False, indent=2))
