import bpy
import os
import json
import shutil

# --- Settings ---
EXPORT_ROOT = bpy.path.abspath("//export")  # relative to current .blend file
MODELS_DIR = os.path.join(EXPORT_ROOT, "models")
TEXTURES_DIR = os.path.join(EXPORT_ROOT, "textures")
JSON_FILE = os.path.join(EXPORT_ROOT, "scene.json")

# Make sure directories exist
os.makedirs(MODELS_DIR, exist_ok=True)
os.makedirs(TEXTURES_DIR, exist_ok=True)

scene_data = []

# Helper to copy textures
def copy_texture(image):
    if not image:
        return None
    src_path = bpy.path.abspath(image.filepath)
    if not os.path.exists(src_path):
        print(f"Texture {image.name} not found at {src_path}")
        return None
    dst_path = os.path.join(TEXTURES_DIR, os.path.basename(src_path))
    shutil.copy(src_path, dst_path)
    return os.path.relpath(dst_path, EXPORT_ROOT).replace("\\", "/")

# Loop through objects
for obj in bpy.data.objects:
    if obj.type == "MESH":
        # Determine shader_type
        shader_type = None
        if "RenderObject" in obj.name:
            shader_type = "renderObject"

        # Ensure object has at least one material with texture
        textures = []
        if obj.material_slots:
            for slot in obj.material_slots:
                mat = slot.material
                if mat and mat.node_tree:
                    for node in mat.node_tree.nodes:
                        if node.type == 'TEX_IMAGE' and node.image:
                            textures.append(copy_texture(node.image))
        if not textures:
            continue  # skip objects without texture

        # Export OBJ
        obj_file = os.path.join(MODELS_DIR, f"{obj.name}.obj")
        bpy.ops.object.select_all(action='DESELECT')
        obj.select_set(True)
        bpy.context.view_layer.objects.active = obj
        bpy.ops.export_scene.obj(
            filepath=obj_file,
            use_selection=True,
            use_materials=True,
            axis_forward='-Z',
            axis_up='Y'
        )

        # Store metadata
        mesh = obj.data
        mesh.calc_loop_triangles()
        scene_data.append({
            "name": obj.name,
            "obj_file": os.path.relpath(obj_file, EXPORT_ROOT).replace("\\", "/"),
            "vertices_count": len(mesh.vertices),
            "indices_count": sum(len(tri.vertices) for tri in mesh.loop_triangles),
            "textures": [tex for tex in textures if tex is not None],
            "shader_type": shader_type
        })

# Write JSON
with open(JSON_FILE, "w") as f:
    json.dump(scene_data, f, indent=4)

print(f"Exported {len(scene_data)} RenderObjects to {EXPORT_ROOT}")
