"""Inspect the supplied local SVG examples. This is not a security sanitizer."""
from pathlib import Path
import json
import sys
import xml.etree.ElementTree as ET

def inspect(filename):
    data = Path(filename).read_bytes()
    if len(data) > 10 * 1024 * 1024:
        raise ValueError("This example limits input to 10 MiB")
    if b"<!DOCTYPE" in data.upper() or b"<!ENTITY" in data.upper():
        raise ValueError("DTD/entity declarations are outside this example's scope")
    root = ET.fromstring(data)
    if root.tag != "{http://www.w3.org/2000/svg}svg":
        raise ValueError("Expected a standalone SVG root with the SVG namespace")
    nodes = list(root.iter())
    local = lambda element: element.tag.rsplit("}", 1)[-1]
    return {
        "file": Path(filename).name,
        "bytes": len(data),
        "paths": sum(local(node) == "path" for node in nodes),
        "images": sum(local(node) == "image" for node in nodes),
        "text_elements": sum(local(node) == "text" for node in nodes),
        "viewBox": root.get("viewBox"),
        "preserveAspectRatio": root.get("preserveAspectRatio", "default"),
        "fill_attributes": sorted({node.get("fill") for node in nodes if node.get("fill")}),
    }

if __name__ == "__main__":
    if len(sys.argv) < 2:
        raise SystemExit("Usage: python inspect-svg.py file.svg [more.svg]")
    for name in sys.argv[1:]:
        print(json.dumps(inspect(name), indent=2))
