"""Read-only URDF archive inspection. Python 3, standard library only.
Usage: python inspect_model.py p1-assembly.zip
No extraction, robot connection or motion commands are performed.
"""
import collections
import hashlib
import json
from pathlib import Path, PurePosixPath
import sys
import xml.etree.ElementTree as ET
import zipfile


def inspect(path):
    result = {"archive": path.name, "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "models": []}
    with zipfile.ZipFile(path) as archive:
        names = set(archive.namelist())
        for name in sorted(names):
            if not name.lower().endswith('.urdf'):
                continue
            data = archive.read(name)
            if len(data) > 10_000_000 or b'<!DOCTYPE' in data.upper() or b'<!ENTITY' in data.upper():
                raise ValueError('Unsupported XML declaration or oversized model: ' + name)
            root = ET.fromstring(data)
            links, joints = root.findall('link'), root.findall('joint')
            link_names = {link.get('name') for link in links}
            parents = [j.find('parent').get('link') for j in joints if j.find('parent') is not None]
            children = [j.find('child').get('link') for j in joints if j.find('child') is not None]
            references = [el.get('filename') for el in root.findall('.//mesh') + root.findall('.//texture')]
            missing, external = set(), set()
            for ref in filter(None, references):
                if '://' in ref:
                    external.add(ref)
                elif str(PurePosixPath(name).parent / ref) not in names:
                    missing.add(ref)
            result['models'].append({
                'file': name, 'links': len(links), 'joints': len(joints),
                'joint_types': dict(collections.Counter(j.get('type') for j in joints)),
                'root_links': sorted(link_names - set(children)),
                'unknown_joint_links': sorted((set(parents) | set(children)) - link_names),
                'inertial_elements': len(root.findall('.//inertial')),
                'collision_elements': len(root.findall('.//collision')),
                'missing_local_assets': sorted(missing), 'external_assets': sorted(external),
            })
    result['scope'] = 'Structural inventory only. Does not validate dynamics, control, calibration or hardware compatibility.'
    return result


if __name__ == '__main__':
    if len(sys.argv) != 2:
        raise SystemExit('Usage: python inspect_model.py path/to/archive.zip')
    try:
        report = inspect(Path(sys.argv[1]))
        print(json.dumps(report, indent=2))
        if not report['models']:
            raise SystemExit('No URDF model found.')
    except (OSError, ValueError, zipfile.BadZipFile, ET.ParseError) as error:
        raise SystemExit(str(error))
