"""Inspect supplied native exports in Blender without calling Hi3D."""

import json
from pathlib import Path
import sys

import bmesh
import bpy

root = Path(sys.argv[sys.argv.index("--") + 1]) if "--" in sys.argv else Path(".")
results = []
for extension in ["glb", "stl"]:
    bpy.ops.object.select_all(action="SELECT")
    bpy.ops.object.delete(use_global=False)
    path = root / f"hi3d-original-cup.{extension}"
    if extension == "glb":
        bpy.ops.import_scene.gltf(filepath=str(path), merge_vertices=True)
    else:
        bpy.ops.wm.stl_import(filepath=str(path), use_mesh_validate=True)
    meshes = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"]
    counts = {
        "file": path.name,
        "objects": len(meshes),
        "triangles": 0,
        "boundaryEdges": 0,
        "nonManifoldEdges": 0,
    }
    for obj in meshes:
        obj.data.calc_loop_triangles()
        counts["triangles"] += len(obj.data.loop_triangles)
        bm = bmesh.new()
        bm.from_mesh(obj.data)
        counts["boundaryEdges"] += sum(e.is_boundary for e in bm.edges)
        counts["nonManifoldEdges"] += sum(not e.is_manifold for e in bm.edges)
        bm.free()
    counts["boundsCoordinateUnits"] = {
        axis: float(meshes[0].dimensions[i]) for i, axis in enumerate(["x", "y", "z"])
    }
    counts["materialNames"] = ", ".join(m.name for m in meshes[0].data.materials if m)
    counts["materialCount"] = len([m for m in meshes[0].data.materials if m])
    results.append(counts)
report = {
    "method": "Blender import inspection of supplied authored fixture",
    "glbMergeVertices": True,
    "results": results,
    "notTested": "Hi3D inference self intersections wall strength slicer or printer",
}
(root / "hi3d-export-check.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report))
