#!/usr/bin/env python3
"""Create a compact verified mobile GLB from reconstructed-v1."""

from __future__ import annotations

import json
import sys
from pathlib import Path

import bmesh
import bpy


def main() -> None:
    args = sys.argv[sys.argv.index("--") + 1 :]
    source = Path(args[0]).resolve()
    output = Path(args[1]).resolve()
    output.parent.mkdir(parents=True, exist_ok=True)
    bpy.ops.import_scene.gltf(filepath=str(source))
    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()
    current = len(obj.data.loop_triangles)
    target = 82_000
    modifier = obj.modifiers.new(name="Mobile optimization", type="DECIMATE")
    modifier.ratio = target / current
    modifier.use_collapse_triangulate = True
    bpy.context.view_layer.objects.active = obj
    bpy.ops.object.modifier_apply(modifier=modifier.name)
    for polygon in obj.data.polygons:
        polygon.use_smooth = True
    bpy.ops.object.select_all(action="DESELECT")
    obj.select_set(True)
    bpy.context.view_layer.objects.active = obj
    bpy.ops.export_scene.gltf(
        filepath=str(output), export_format="GLB", use_selection=True, export_apply=True,
        export_yup=True, export_normals=True, export_tangents=False, export_texcoords=False,
        export_materials="EXPORT", export_animations=False, export_cameras=False,
        export_lights=False, export_draco_mesh_compression_enable=False,
    )
    obj.data.calc_loop_triangles()
    editable = bmesh.new()
    editable.from_mesh(obj.data)
    result = {
        "source": str(source), "output": str(output), "bytes": output.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),
    }
    editable.free()
    output.with_suffix(".json").write_text(json.dumps(result, indent=2), encoding="utf-8")
    print("TN_MOBILE", json.dumps(result))


if __name__ == "__main__":
    main()
