"""Create an original cube and compare Blender glTF modifier-export settings.

Run only in a separate background Blender process with factory startup and
automatic script execution disabled. Supply a NEW output directory after --:
Blender --background --factory-startup --disable-autoexec --python-exit-code 1 \
  --python blender-gltf-demo.py -- --output-dir /new/output/directory

No existing scene, asset, add-on, account or network connection is used.
The output directory contains the synthetic .blend, two .glb files and JSON.
"""
import argparse
import datetime
import hashlib
import json
import pathlib
import struct
import sys

import bpy


def read_glb(path):
    raw = path.read_bytes()
    magic, version, length = struct.unpack_from("<4sII", raw)
    assert magic == b"glTF" and version == 2 and length == len(raw)
    offset, document = 12, None
    while offset < len(raw):
        chunk_length, chunk_type = struct.unpack_from("<II", raw, offset)
        offset += 8
        if chunk_type == 0x4E4F534A:
            document = json.loads(raw[offset:offset + chunk_length].decode("utf-8"))
        offset += chunk_length
    assert document is not None and offset == len(raw)
    primitives = [p for mesh in document["meshes"] for p in mesh["primitives"]]
    assert all(p.get("mode", 4) == 4 and "indices" in p for p in primitives)
    indices = sum(document["accessors"][p["indices"]]["count"] for p in primitives)
    assert indices % 3 == 0
    positions = sum(document["accessors"][p["attributes"]["POSITION"]]["count"] for p in primitives)
    return {"file": path.name, "bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest(),
            "gltf_version": document["asset"]["version"], "mesh_count": len(document["meshes"]),
            "primitive_count": len(primitives), "position_entries": positions,
            "triangle_indices": indices, "triangles": indices // 3,
            "skins": len(document.get("skins", [])), "animations": len(document.get("animations", []))}


def mesh_state(obj):
    mesh = obj.data
    mesh.calc_loop_triangles()
    return {"name": obj.name, "vertices": len(mesh.vertices), "polygons": len(mesh.polygons),
            "triangles": len(mesh.loop_triangles),
            "modifiers": [{"name": m.name, "type": m.type,
                           **({"levels": m.levels, "render_levels": m.render_levels} if m.type == "SUBSURF" else {})}
                          for m in obj.modifiers]}


def main():
    if not bpy.app.background or "--factory-startup" not in sys.argv or "--disable-autoexec" not in sys.argv:
        raise SystemExit("Use a separate --background --factory-startup --disable-autoexec Blender process.")
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output-dir", type=pathlib.Path, required=True)
    args = parser.parse_args(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [])
    destination = args.output_dir.resolve()
    destination.mkdir(exist_ok=False)  # Never overwrite an existing directory.

    bpy.ops.wm.read_factory_settings(use_empty=True)
    bpy.context.scene.unit_settings.system = "METRIC"
    bpy.context.scene.unit_settings.scale_length = 1.0
    bpy.ops.mesh.primitive_cube_add(size=2.0, location=(0, 0, 0))
    cube = bpy.context.active_object
    cube.name = "SoftwareRadarDemoCube"
    modifier = cube.modifiers.new("DemoSubdivision", "SUBSURF")
    modifier.subdivision_type = "CATMULL_CLARK"
    modifier.levels = 1
    modifier.render_levels = 1
    native_before = mesh_state(cube)
    evaluated_object = cube.evaluated_get(bpy.context.evaluated_depsgraph_get())
    evaluated_mesh = evaluated_object.to_mesh()
    evaluated_mesh.calc_loop_triangles()
    evaluated = {"vertices": len(evaluated_mesh.vertices), "polygons": len(evaluated_mesh.polygons),
                 "triangles": len(evaluated_mesh.loop_triangles)}
    evaluated_object.to_mesh_clear()
    assert native_before["vertices"] == 8 and native_before["polygons"] == 6
    assert evaluated == {"vertices": 26, "polygons": 24, "triangles": 48}

    native_path = destination / "subdivision-cube.blend"
    bpy.ops.wm.save_as_mainfile(filepath=str(native_path), check_existing=False)
    exports = {}
    for apply_modifiers, filename in [(False, "cube-base-mesh.glb"), (True, "cube-evaluated-mesh.glb")]:
        path = destination / filename
        bpy.ops.export_scene.gltf(filepath=str(path), export_format="GLB", use_selection=True,
                                  export_apply=apply_modifiers, export_animations=False,
                                  export_materials="NONE", export_cameras=False, export_lights=False)
        exports["evaluated" if apply_modifiers else "base"] = {
            "export_apply": apply_modifiers, **read_glb(path)}
    assert exports["base"]["triangles"] == 12 and exports["evaluated"]["triangles"] == 48
    assert exports["base"]["skins"] == exports["evaluated"]["skins"] == 0

    bpy.ops.wm.open_mainfile(filepath=str(native_path), load_ui=False)
    native_reopened = mesh_state(bpy.data.objects["SoftwareRadarDemoCube"])
    assert native_reopened == native_before

    bpy.ops.wm.read_factory_settings(use_empty=True)
    bpy.ops.import_scene.gltf(filepath=str(destination / "cube-evaluated-mesh.glb"))
    imported_meshes = [mesh_state(obj) for obj in bpy.context.scene.objects if obj.type == "MESH"]
    assert len(imported_meshes) == 1 and imported_meshes[0]["triangles"] == 48
    assert imported_meshes[0]["modifiers"] == []
    observed = {"schema_version": 1, "observed_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
                "blender_version": bpy.app.version_string,
                "fixture": "One original two-unit cube with one Catmull-Clark Subdivision modifier at viewport and render level 1; no rig, animation, material or external asset.",
                "native_before_export": native_before, "evaluated_mesh": evaluated,
                "exports": exports, "native_reopened": native_reopened,
                "evaluated_glb_reimport": imported_meshes,
                "scope": "Blender-only synthetic file exercise. No Maya evaluation, cross-application acceptance, animation, materials, performance or production asset test."}
    (destination / "observations.json").write_text(json.dumps(observed, indent=2) + "\n", encoding="utf-8")
    print("SOFTWARERADAR_GLTF_RESULT " + json.dumps(observed))


if __name__ == "__main__":
    main()
