"""Ciclo 83 (i20): mide qué llega a un GLB exportado desde Blender: modificadores (con y sin «Apply Modifiers») y materiales.

Uso: herramientas/blender -b --factory-startup --python guias/medir_glb.py -- salida.json
Escena: 4 objetos con modificadores (Mirror, Subdivision Surface nivel 2, Bevel, Array x3) y 5 cubos con materiales
distintos (Principled simple, emisión, textura de imagen, textura procedural Noise, Mix Shader). Exporta GLB con los
ajustes por defecto y con Apply Modifiers; lee el JSON del GLB (triángulos por malla, materiales, texturas) y lo compara
con los triángulos que Blender evalúa (con modificadores) y sin evaluar (malla base).
"""
import json
import os
import struct
import sys
import tempfile

import bpy

salida = sys.argv[sys.argv.index("--") + 1]


def material(nombre, tipo):
    m = bpy.data.materials.new(nombre)
    m.use_nodes = True
    nt = m.node_tree
    bsdf = nt.nodes.get("Principled BSDF")
    if tipo == "simple":
        bsdf.inputs["Base Color"].default_value = (0.8, 0.1, 0.1, 1)
        bsdf.inputs["Metallic"].default_value = 1.0
        bsdf.inputs["Roughness"].default_value = 0.3
    elif tipo == "emision":
        bsdf.inputs["Emission Color"].default_value = (0.1, 0.9, 0.2, 1)
        bsdf.inputs["Emission Strength"].default_value = 5.0
    elif tipo == "imagen":
        img = bpy.data.images.new("tex_checker", 64, 64)
        img.generated_type = "COLOR_GRID"
        img.pack()
        tex = nt.nodes.new("ShaderNodeTexImage")
        tex.image = img
        nt.links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])
    elif tipo == "noise":
        tex = nt.nodes.new("ShaderNodeTexNoise")
        nt.links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])
    elif tipo == "mix":
        out = nt.nodes.get("Material Output")
        b2 = nt.nodes.new("ShaderNodeBsdfPrincipled")
        b2.inputs["Base Color"].default_value = (0.1, 0.1, 0.9, 1)
        mix = nt.nodes.new("ShaderNodeMixShader")
        mix.inputs["Fac"].default_value = 0.5
        nt.links.new(bsdf.outputs["BSDF"], mix.inputs[1])
        nt.links.new(b2.outputs["BSDF"], mix.inputs[2])
        nt.links.new(mix.outputs["Shader"], out.inputs["Surface"])
    return m


def escena():
    bpy.ops.wm.read_factory_settings(use_empty=True)
    bpy.ops.mesh.primitive_cube_add(location=(0, 0, 0))
    o = bpy.context.active_object
    o.name = "Mirror"
    o.modifiers.new("Mirror", "MIRROR")
    bpy.ops.mesh.primitive_cube_add(location=(3, 0, 0))
    o = bpy.context.active_object
    o.name = "Subdivision"
    o.modifiers.new("Subdivision", "SUBSURF").levels = 2
    bpy.ops.mesh.primitive_cube_add(location=(6, 0, 0))
    o = bpy.context.active_object
    o.name = "Bevel"
    b = o.modifiers.new("Bevel", "BEVEL")
    b.width = 0.1
    b.segments = 3
    bpy.ops.mesh.primitive_cube_add(location=(9, 0, 0))
    o = bpy.context.active_object
    o.name = "Array"
    o.modifiers.new("Array", "ARRAY").count = 3
    for k, tipo in enumerate(["simple", "emision", "imagen", "noise", "mix"]):
        bpy.ops.mesh.primitive_cube_add(location=(k * 3, 5, 0))
        o = bpy.context.active_object
        o.name = "Mat_" + tipo
        o.data.materials.append(material("M_" + tipo, tipo))
    dg = bpy.context.evaluated_depsgraph_get()
    tris = {}
    for o in bpy.data.objects:
        if o.type != "MESH":
            continue
        base = o.data
        base.calc_loop_triangles()
        ev = o.evaluated_get(dg).to_mesh()
        ev.calc_loop_triangles()
        tris[o.name] = {"base": len(base.loop_triangles), "evaluado": len(ev.loop_triangles)}
        o.evaluated_get(dg).to_mesh_clear()
    return tris


def leer_glb(ruta):
    with open(ruta, "rb") as f:
        data = f.read()
    largo = struct.unpack_from("<I", data, 12)[0]
    js = json.loads(data[20:20 + largo].decode("utf-8"))
    acc = js.get("accessors", [])
    nodos = {n.get("name"): n for n in js.get("nodes", [])}
    mallas = {}
    for nombre, n in nodos.items():
        if "mesh" not in n:
            continue
        mesh = js["meshes"][n["mesh"]]
        t = 0
        mats = []
        for p in mesh["primitives"]:
            if "indices" in p:
                t += acc[p["indices"]]["count"] // 3
            else:
                t += acc[p["attributes"]["POSITION"]]["count"] // 3
            if "material" in p:
                mats.append(p["material"])
        mallas[nombre] = {"triangulos": t, "materiales": mats}
    materiales = []
    for m in js.get("materials", []):
        pbr = m.get("pbrMetallicRoughness", {})
        materiales.append({
            "nombre": m.get("name"),
            "baseColorFactor": [round(x, 4) for x in pbr.get("baseColorFactor", [1, 1, 1, 1])],
            "metallicFactor": pbr.get("metallicFactor", 1.0),
            "roughnessFactor": round(pbr.get("roughnessFactor", 1.0), 4),
            "baseColorTexture": "baseColorTexture" in pbr,
            "emissiveFactor": [round(x, 4) for x in m.get("emissiveFactor", [0, 0, 0])],
            "emissiveStrength": m.get("extensions", {}).get("KHR_materials_emissive_strength", {}).get("emissiveStrength"),
        })
    return {"mallas": mallas, "materiales": materiales, "imagenes": len(js.get("images", [])),
            "extensiones": js.get("extensionsUsed", [])}


res = {"blender": bpy.app.version_string, "variantes": {}}
tmp = tempfile.mkdtemp(prefix="medir_glb_")
for nombre, op in [("glb_default", {}), ("glb_apply_modifiers", {"export_apply": True})]:
    tris = escena()
    ruta = os.path.join(tmp, nombre + ".glb")
    bpy.ops.export_scene.gltf(filepath=ruta, export_format="GLB", **op)
    d = leer_glb(ruta)
    d["opciones"] = op
    d["triangulos_blender"] = tris
    res["variantes"][nombre] = d
json.dump(res, open(salida, "w"), indent=1)
print("MEDIDO_GLB", bpy.app.version_string)
