import bpy, sys, os
import bmesh
sys.path.insert(0, os.getcwd() + "/assets/blender/scripts")
from settings import basepath

def split_mesh_by_material(obj):
    """Splits a mesh object into separate objects based on material assignments."""

    if obj.type != 'MESH':
        return

    mesh = obj.data
    bm = bmesh.new()
    bm.from_mesh(mesh)

    material_indices = {}
    for face in bm.faces:
        material_index = face.material_index
        if material_index not in material_indices:
            material_indices[material_index] = []
        material_indices[material_index].append(face)
    
    for material_index, faces in material_indices.items():
        new_bm = bmesh.new()
        for face in faces:
            new_bm.faces.new([new_bm.verts.new(v.co) for v in face.verts])
        
        new_mesh = bpy.data.meshes.new(f"{obj.name}_mat_{material_index}")
        new_bm.to_mesh(new_mesh)
        new_bm.free()
        
        new_obj = bpy.data.objects.new(f"{obj.name}_mat_{material_index}", new_mesh)
        new_obj.data.materials.append(mesh.materials[material_index])
        bpy.context.collection.objects.link(new_obj)

def append_object(filepath, object_names):
    """Appends an object from a specified Blender file.

    Args:
        filepath (str): The full path to the source .blend file.
        object_name (str): The name of the object to append.
    """
    with bpy.data.libraries.load(filepath) as (data_from, data_to):
        data_to.objects = object_names

    if data_to.objects:
        for obj in data_to.objects:
             bpy.context.collection.objects.link(obj)
    else:
        print(f"Object '{object_name}' not found in '{filepath}'.")

bpy.ops.wm.read_homefile(use_empty=True)
for o in bpy.data.objects:
    bpy.data.objects.remove(o)

append_object(basepath + "/assets/blender/" + "vrm-vroid-normal-male.blend", ["Body", "male"])

bpy.ops.wm.save_as_mainfile(filepath=basepath + "/" + "tmp.blend")

