#!/usr/bin/env python3
"""xmlpeek — summarize an XML file: tag counts, depth, attributes.
Usage: xmlpeek [--max-tags N] FILE
Answers "what is in this XML?" without dumping megabytes of angle brackets:
root element, total elements, max depth, a ranked tag census, and which
attributes each tag carries.
"""
import argparse, collections, sys
import xml.etree.ElementTree as ET


def walk(elem, depth, counts, attrs, max_depth):
    counts[elem.tag] += 1
    max_depth[0] = max(max_depth[0], depth)
    for k in elem.attrib:
        attrs[elem.tag].add(k)
    for child in elem:
        walk(child, depth + 1, counts, attrs, max_depth)


def main(argv=None):
    ap = argparse.ArgumentParser(prog="xmlpeek",
        description="Summarize an XML file: tag counts, depth, attributes.")
    ap.add_argument("file", help="XML file")
    ap.add_argument("--max-tags", type=int, default=30, help="tags shown in the census (default 30)")
    ap.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
    argv_list = list(argv) if argv is not None else sys.argv[1:]
    if "--selftest" in argv_list:
        return selftest()
    a = ap.parse_args(argv)
    if a.selftest:
        return selftest()
    try:
        tree = ET.parse(a.file)
    except OSError as e:
        print(f"xmlpeek: {e}", file=sys.stderr)
        return 1
    except ET.ParseError as e:
        print(f"xmlpeek: invalid XML: {e}", file=sys.stderr)
        return 1
    root = tree.getroot()
    counts = collections.Counter()
    attrs = collections.defaultdict(set)
    max_depth = [0]
    walk(root, 1, counts, attrs, max_depth)
    total = sum(counts.values())
    print(f"xmlpeek: {a.file}")
    print(f"root: <{root.tag}>  elements: {total}  distinct tags: {len(counts)}  max depth: {max_depth[0]}")
    print(f"{'count':>7}  {'tag':<28} attributes")
    for tag, n in counts.most_common(a.max_tags):
        at = ", ".join(sorted(attrs[tag])) if attrs[tag] else "-"
        print(f"{n:>7}  {tag:<28} {at}")
    return 0


def selftest():
    import tempfile, os, io
    from contextlib import redirect_stdout
    data = ('<catalog><book id="1" lang="en"><title>One</title><price>9.99</price></book>'
            '<book id="2"><title>Two</title><price>5.00</price></book></catalog>')
    with tempfile.NamedTemporaryFile("w", suffix=".xml", delete=False) as fh:
        fh.write(data)
        path = fh.name
    try:
        buf = io.StringIO()
        with redirect_stdout(buf):
            rc = main([path])
        out = buf.getvalue()
        assert rc == 0, out
        assert "elements: 7" in out and "max depth: 3" in out, out
        assert "book" in out and "id, lang" in out, out
    finally:
        os.unlink(path)
    print("xmlpeek selftest: PASS")
    return 0


if __name__ == "__main__":
    sys.exit(main())
