"""Ciclo 83 (i20): ¿qué animaciones llegan a un GLB de Blender? Mide con cada «Animation mode» del exportador glTF.

Uso: herramientas/blender -b --factory-startup --python guias/medir_anim.py -- carpeta_salida
Escena (24 fps): «Spinner» con la acción ACTIVA «Spin» (gira 360° en Z, cuadros 1-48) y una segunda acción «Bounce»
(sube y baja, 1-24) guardada con usuario falso pero NO asignada; «Slider» con su acción «Slide» (1-72) empujada a una pista
NLA (sin acción activa). Exporta GLB con los modos ACTIONS (por defecto), ACTIVE_ACTIONS, NLA_TRACKS y SCENE, y lee del
JSON de cada GLB las animaciones: nombre, canales, nodos animados y duración (máximo del acceso de tiempos).
Escribe carpeta_salida/<modo>.glb y carpeta_salida/anim.json (para importarlos después en Godot).
"""
import json
import os
import struct
import sys

import bpy

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


def escena(bounce_en_nla=False):
    bpy.ops.wm.read_factory_settings(use_empty=True)
    sc = bpy.context.scene
    sc.render.fps = 24
    sc.frame_start, sc.frame_end = 1, 72
    bpy.ops.mesh.primitive_cube_add(location=(0, 0, 0))
    a = bpy.context.active_object
    a.name = "Spinner"
    a.animation_data_create()
    bounce = bpy.data.actions.new("Bounce")
    bounce.use_fake_user = True
    a.animation_data.action = bounce
    a.location = (0, 0, 0)
    a.keyframe_insert("location", index=2, frame=1)
    a.location = (0, 0, 2)
    a.keyframe_insert("location", index=2, frame=12)
    a.location = (0, 0, 0)
    a.keyframe_insert("location", index=2, frame=24)
    spin = bpy.data.actions.new("Spin")
    a.animation_data.action = spin
    a.rotation_euler = (0, 0, 0)
    a.keyframe_insert("rotation_euler", index=2, frame=1)
    a.rotation_euler = (0, 0, 6.283185)
    a.keyframe_insert("rotation_euler", index=2, frame=48)
    if bounce_en_nla:
        pista_b = a.animation_data.nla_tracks.new()
        pista_b.strips.new("Bounce", 1, bounce)
    bpy.ops.mesh.primitive_cube_add(location=(4, 0, 0))
    b = bpy.context.active_object
    b.name = "Slider"
    b.animation_data_create()
    slide = bpy.data.actions.new("Slide")
    b.animation_data.action = slide
    b.location = (4, 0, 0)
    b.keyframe_insert("location", index=0, frame=1)
    b.location = (8, 0, 0)
    b.keyframe_insert("location", index=0, frame=72)
    pista = b.animation_data.nla_tracks.new()
    pista.strips.new("Slide", 1, slide)
    b.animation_data.action = None
    return {"Spinner": {"activa": a.animation_data.action.name if a.animation_data.action else None},
            "Slider": {"activa": None, "nla": [s.name for t in b.animation_data.nla_tracks for s in t.strips]},
            "acciones": sorted(x.name for x in bpy.data.actions)}


def leer(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"))
    nodos = js.get("nodes", [])
    acc = js.get("accessors", [])
    out = []
    for an in js.get("animations", []):
        dur = 0.0
        objetivos = set()
        for ch in an["channels"]:
            objetivos.add(nodos[ch["target"]["node"]].get("name", "?") + "." + ch["target"]["path"])
            s = an["samplers"][ch["sampler"]]
            dur = max(dur, acc[s["input"]]["max"][0])
        out.append({"nombre": an.get("name"), "canales": len(an["channels"]), "objetivos": sorted(objetivos),
                    "duracion_s": round(dur, 4)})
    return out


MODOS = ["ACTIONS", "ACTIVE_ACTIONS", "NLA_TRACKS", "SCENE", "BROADCAST", "ACTIONS_BOUNCE_NLA"]
disponibles = [i.identifier for i in bpy.ops.export_scene.gltf.get_rna_type().properties["export_animation_mode"].enum_items]
res = {"blender": bpy.app.version_string, "modos": {}, "modos_disponibles": disponibles}
for modo in MODOS:
    real = "ACTIONS" if modo == "ACTIONS_BOUNCE_NLA" else modo
    if real not in disponibles:
        continue
    info = escena(bounce_en_nla=(modo == "ACTIONS_BOUNCE_NLA"))
    ruta = os.path.join(salida, f"{modo.lower()}.glb")
    op = {} if real == "ACTIONS" else {"export_animation_mode": real}
    bpy.ops.export_scene.gltf(filepath=ruta, export_format="GLB", **op)
    res["modos"][modo] = {"opciones": op, "animaciones": leer(ruta)}
res["escena"] = info
json.dump(res, open(os.path.join(salida, "anim.json"), "w"), indent=1)
print("MEDIDO_ANIM", bpy.app.version_string)
