#!/usr/bin/env python3
"""Re-import generated GLBs and verify geometry/material invariants."""

from __future__ import annotations

import json
import sys
from pathlib import Path

import bmesh
import bpy


def clear_scene() -> None:
    bpy.ops.object.select_all(action="SELECT")
    bpy.ops.object.delete(use_global=False)


def verify(path: Path) -> dict:
    clear_scene()
    bpy.ops.import_scene.gltf(filepath=str(path))
    obj = max(
        (candidate for candidate in bpy.context.scene.objects if candidate.type == "MESH"),
        key=lambda candidate: len(candidate.data.vertices),
    )
    obj.data.calc_loop_triangles()
    editable = bmesh.new()
    editable.from_mesh(obj.data)
    boundary_edges = sum(1 for edge in editable.edges if edge.is_boundary)
    non_manifold_edges = sum(1 for edge in editable.edges if not edge.is_manifold)
    editable.free()

    material = obj.data.materials[0]
    principled = material.node_tree.nodes.get("Principled BSDF")
    return {
        "path": str(path),
        "bytes": path.stat().st_size,
        "vertices": len(obj.data.vertices),
        "triangles": len(obj.data.loop_triangles),
        "boundary_edges": boundary_edges,
        "non_manifold_edges": non_manifold_edges,
        "material": material.name,
        "base_color": [round(value, 6) for value in principled.inputs["Base Color"].default_value],
        "metallic": round(principled.inputs["Metallic"].default_value, 6),
        "roughness": round(principled.inputs["Roughness"].default_value, 6),
    }


def main() -> None:
    paths = [Path(value).resolve() for value in sys.argv[sys.argv.index("--") + 1 :]]
    result = {"valid": True, "models": [verify(path) for path in paths]}
    result["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 result["models"]
    )
    output = paths[0].parent / "verification.json"
    output.write_text(json.dumps(result, indent=2), encoding="utf-8")
    print("TN_VERIFICATION", json.dumps(result))
    if not result["valid"]:
        raise SystemExit(1)


if __name__ == "__main__":
    main()
