#!/usr/bin/env python3
"""Re-import and verify reconstructed web/mobile GLBs."""

from __future__ import annotations

import json
import sys
from pathlib import Path

import bmesh
import bpy


def verify(path: Path) -> dict:
    bpy.ops.object.select_all(action="SELECT")
    bpy.ops.object.delete(use_global=False)
    bpy.ops.import_scene.gltf(filepath=str(path))
    obj = max((candidate for candidate in bpy.context.scene.objects if candidate.type == "MESH"), key=lambda item: len(item.data.vertices))
    obj.data.calc_loop_triangles()
    editable = bmesh.new()
    editable.from_mesh(obj.data)
    material = obj.data.materials[0]
    node = material.node_tree.nodes.get("Principled BSDF")
    result = {
        "path": str(path), "bytes": path.stat().st_size,
        "vertices": len(obj.data.vertices), "triangles": len(obj.data.loop_triangles),
        "boundary_edges": sum(edge.is_boundary for edge in editable.edges),
        "non_manifold_edges": sum(not edge.is_manifold for edge in editable.edges),
        "dimensions": [round(value, 6) for value in obj.dimensions],
        "metallic": round(node.inputs["Metallic"].default_value, 6),
        "roughness": round(node.inputs["Roughness"].default_value, 6),
    }
    editable.free()
    return result


def main() -> None:
    paths = [Path(value).resolve() for value in sys.argv[sys.argv.index("--") + 1 :]]
    models = [verify(path) for path in paths]
    valid = all(
        model["boundary_edges"] == 0 and model["non_manifold_edges"] == 0
        and model["metallic"] == 1.0 and 0.04 <= model["roughness"] <= 0.09
        for model in models
    )
    result = {"valid": valid, "models": models}
    output = paths[0].parent / "verification.json"
    output.write_text(json.dumps(result, indent=2), encoding="utf-8")
    print("TN_FINAL_VERIFICATION", json.dumps(result))
    if not valid:
        raise SystemExit(1)


if __name__ == "__main__":
    main()
