"""Ciclo 83 (i20): ¿llegan las texturas en un FBX de Blender? Exporta 2 cubos con textura de imagen (una EMPAQUETADA en el
.blend y otra GUARDADA como archivo PNG al lado del .blend) con varias opciones de «Path Mode» y «Embed Textures», lee cada
FBX (nodos Video/Texture: nombre de archivo y bytes incrustados) y deja los archivos en una carpeta para importarlos en Godot.

Uso: herramientas/blender -b --factory-startup --python guias/exportar_texturas.py -- carpeta_salida
Escribe carpeta_salida/<variante>/modelo.fbx (+ lo que copie Blender) y carpeta_salida/fbx_texturas.json.
"""
import json
import os
import sys

import bpy

from io_scene_fbx import parse_fbx

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


def mat_con_imagen(nombre, img):
    m = bpy.data.materials.new(nombre)
    m.use_nodes = True
    nt = m.node_tree
    tex = nt.nodes.new("ShaderNodeTexImage")
    tex.image = img
    nt.links.new(tex.outputs["Color"], nt.nodes["Principled BSDF"].inputs["Base Color"])
    return m


def escena():
    bpy.ops.wm.read_factory_settings(use_empty=True)
    bpy.ops.wm.save_as_mainfile(filepath=os.path.join(FUENTE, "escena.blend"))
    g = bpy.data.images.new("tmp_color_grid", 64, 64)
    g.generated_type = "COLOR_GRID"
    ruta_tmp = os.path.join(FUENTE, "tex_empaquetada.png")
    g.filepath_raw = ruta_tmp
    g.file_format = "PNG"
    g.save()
    bpy.data.images.remove(g)
    a = bpy.data.images.load(ruta_tmp)
    a.name = "tex_empaquetada"
    a.pack()
    os.remove(ruta_tmp)  # el único original queda DENTRO del .blend
    b = bpy.data.images.new("tex_archivo", 64, 64)
    b.generated_type = "UV_GRID"
    b.filepath_raw = os.path.join(FUENTE, "tex_archivo.png")
    b.file_format = "PNG"
    b.save()
    bpy.ops.mesh.primitive_cube_add(location=(0, 0, 0))
    o = bpy.context.active_object
    o.name = "Cubo_empaquetada"
    o.data.materials.append(mat_con_imagen("M_empaquetada", a))
    bpy.ops.mesh.primitive_cube_add(location=(3, 0, 0))
    o = bpy.context.active_object
    o.name = "Cubo_archivo"
    o.data.materials.append(mat_con_imagen("M_archivo", b))
    bpy.ops.wm.save_mainfile()


def leer_videos(ruta):
    raiz, _ = parse_fbx.parse(ruta)
    objs = next(e for e in raiz.elems if e.id == b"Objects")
    out = []
    for e in objs.elems:
        if e.id == b"Video":
            info = {"nombre": e.props[1].split(b"\x00")[0].decode("utf-8", "replace"), "bytes_incrustados": 0}
            for s in e.elems:
                if s.id == b"Content" and s.props and isinstance(s.props[0], (bytes, bytearray)):
                    info["bytes_incrustados"] = len(s.props[0])
                if s.id == b"RelativeFilename":
                    info["relativo"] = s.props[0].decode("utf-8", "replace") if isinstance(s.props[0], bytes) else s.props[0]
                if s.id == b"Filename":
                    info["absoluto"] = s.props[0].decode("utf-8", "replace") if isinstance(s.props[0], bytes) else s.props[0]
            out.append(info)
    return out


VARIANTES = [
    ("fbx_defaults", dict()),
    ("fbx_copy_embed", dict(path_mode="COPY", embed_textures=True)),
    ("fbx_copy", dict(path_mode="COPY")),
    ("fbx_relative", dict(path_mode="RELATIVE")),
]
res = {"blender": bpy.app.version_string, "variantes": {}}
for nombre, op in VARIANTES:
    escena()
    carpeta = os.path.join(salida, nombre)
    os.makedirs(carpeta, exist_ok=True)
    ruta = os.path.join(carpeta, "modelo.fbx")
    bpy.ops.export_scene.fbx(filepath=ruta, object_types={"MESH"}, **op)
    res["variantes"][nombre] = {"opciones": op, "videos": leer_videos(ruta),
                                "archivos_junto_al_fbx": sorted(f for f in os.listdir(carpeta) if f != "modelo.fbx"),
                                "bytes_fbx": os.path.getsize(ruta),
                                "contenido_fbm": sorted(os.listdir(os.path.join(carpeta, "modelo.fbm")))
                                if os.path.isdir(os.path.join(carpeta, "modelo.fbm")) else []}
json.dump(res, open(os.path.join(salida, "fbx_texturas.json"), "w"), indent=1)
print("EXPORTADO_TEXTURAS", bpy.app.version_string)
