"""Ciclo 83 (i20): exporta una escena de prueba de Blender a GLB y FBX con varias opciones, para importarla en Godot
(guias/medir_godot.gd) y medir lo que Godot construye de verdad.

Uso: herramientas/blender -b --factory-startup --python guias/exportar_godot.py -- carpeta_salida
Escena (tamaños en Blender, todas con escala aplicada salvo la indicada):
  Crate_1x2x3            1 x 2 x 3 m (ALTO 3 en Z), en (0, 0, 0)
  Crate_unapplied_0.5    malla 2 x 4 x 6 con escala de objeto 0,5 SIN aplicar (mide 1 x 2 x 3), en (3, 1, 0)
  Wall-col               4 x 0,2 x 2, en (-4, 0, 0)       sufijo -col
  Floor_col              6 x 6 x 0,1, en (0, 6, 0)        sufijo _col (guion bajo)
  Ramp-convcol           2 x 2 x 1, en (6, 0, 0)          sufijo -convcol
  Barrel-colonly         cilindro r 0,5 alto 1, en (9, 0, 0)    sufijo -colonly
  Rock-convcolonly       esfera ico r 0,6, en (12, 0, 0)  sufijo -convcolonly
  Box-rigid              1 x 1 x 1, en (15, 0, 0)         sufijo -rigid
  Helper-noimp           1 x 1 x 1, en (18, 0, 0)         sufijo -noimp
  Crate-COL              1 x 1 x 1, en (21, 0, 0)         sufijo en MAYÚSCULAS
"""
import json
import os
import sys

import bpy

salida = sys.argv[sys.argv.index("--") + 1]
os.makedirs(salida, exist_ok=True)


def caja(nombre, dims, loc, size=1.0):
    bpy.ops.mesh.primitive_cube_add(size=size, location=loc)
    o = bpy.context.active_object
    o.name = nombre
    o.scale = dims
    bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
    return o


def escena():
    bpy.ops.wm.read_factory_settings(use_empty=True)
    caja("Crate_1x2x3", (1, 2, 3), (0, 0, 0))
    b = caja("Crate_unapplied_0.5", (1, 2, 3), (3, 1, 0), size=2.0)
    b.scale = (0.5, 0.5, 0.5)
    caja("Wall-col", (4, 0.2, 2), (-4, 0, 0))
    caja("Floor_col", (6, 6, 0.1), (0, 6, 0))
    caja("Ramp-convcol", (2, 2, 1), (6, 0, 0))
    bpy.ops.mesh.primitive_cylinder_add(radius=0.5, depth=1.0, location=(9, 0, 0))
    bpy.context.active_object.name = "Barrel-colonly"
    bpy.ops.mesh.primitive_ico_sphere_add(radius=0.6, location=(12, 0, 0))
    bpy.context.active_object.name = "Rock-convcolonly"
    caja("Box-rigid", (1, 1, 1), (15, 0, 0))
    caja("Helper-noimp", (1, 1, 1), (18, 0, 0))
    caja("Crate-COL", (1, 1, 1), (21, 0, 0))
    bpy.context.view_layer.update()
    return {o.name: {"dims": [round(x, 4) for x in o.dimensions], "loc": [round(x, 4) for x in o.location],
                     "scale": [round(x, 4) for x in o.scale]} for o in bpy.data.objects}


VARIANTES = [
    ("glb_default", "gltf", dict(export_format="GLB")),
    ("glb_yup_off", "gltf", dict(export_format="GLB", export_yup=False)),
    ("fbx_default", "fbx", dict()),
    ("fbx_scale_all", "fbx", dict(apply_scale_options="FBX_SCALE_ALL")),
    ("fbx_scale_all_apply_transform", "fbx", dict(apply_scale_options="FBX_SCALE_ALL", bake_space_transform=True)),
]

info = {"blender": bpy.app.version_string, "variantes": {}}
for nombre, tipo, op in VARIANTES:
    datos = escena()
    if tipo == "gltf":
        ruta = os.path.join(salida, nombre + ".glb")
        bpy.ops.export_scene.gltf(filepath=ruta, **op)
    else:
        ruta = os.path.join(salida, nombre + ".fbx")
        bpy.ops.export_scene.fbx(filepath=ruta, object_types={"MESH"}, **op)
    info["variantes"][nombre] = {"archivo": os.path.basename(ruta), "opciones": op}
info["escena_blender"] = datos
json.dump(info, open(os.path.join(salida, "exportado.json"), "w"), indent=1)
print("EXPORTADO", bpy.app.version_string, sorted(os.listdir(salida)))
