import bpy
import os, sys, time
argv = sys.argv
argv = argv[argv.index("--") + 1:]

incpath = os.path.dirname(__file__)

sys.path.insert(0, incpath)
outdir = argv[0]

def export_root_objects_to_gltf(output_dir):
    # Ensure the output directory exists
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # Deselect all objects
    bpy.ops.object.select_all(action='DESELECT')

    # Iterate through all objects in the scene
    for obj in bpy.context.scene.objects:
        # Check if the object has no parent and has children
        # The original request specifies "objects having no parent with children".
        # This condition captures those that are explicitly root objects of a hierarchy.
        if obj.parent is None:
            # Select the root object and all its children
            print(obj.name)
            obj.select_set(True)
            for child in obj.children_recursive:
                child.select_set(True)
            
            # Set the root object as the active object for the export operator
            bpy.context.view_layer.objects.active = obj

            # Define the output file path
            file_path = os.path.join(output_dir, f"{obj.name}.glb")
            
            # Export the selected objects to a glTF file
            bpy.ops.export_scene.gltf(filepath=file_path,
                    use_selection=True,
                    check_existing=False,
                    export_format='GLB',
                    export_texture_dir='textures', export_texcoords=True,
                    export_normals=True,
                    export_tangents=True,
                    export_materials='EXPORT',
                    export_colors=True,
                    use_mesh_edges=False,
                    use_mesh_vertices=False,
                    export_cameras=False,
                    use_visible=False,
                    use_renderable=False,
                    export_yup=True,
                    export_apply=True,
                    export_animations=True,
                    export_force_sampling=True,
                    export_def_bones=False,
                    export_current_frame=False,
                    export_morph=True,
                    export_morph_animation=False,
                    export_morph_normal=True,
                    export_morph_tangent=True,
                    export_lights=False,
                    export_skins=True)

            # Deselect all objects for the next iteration
            bpy.ops.object.select_all(action='DESELECT')
            
            print(f"Exported {obj.name} and its children to {file_path}")

export_root_objects_to_gltf(outdir)

