import bpy
import sys
import os

def process_append(source_files, output_path):
    required_props = {"age", "sex", "slot"}
    
    for file_path in source_files:
        if not os.path.exists(file_path):
            print(f"Warning: Source file not found: {file_path}")
            continue

        with bpy.data.libraries.load(file_path) as (data_from, data_to):
            data_to.objects = data_from.objects

        for obj in data_to.objects:
            if obj is None: continue
            
            # Check criteria
            has_props = all(p in obj.keys() for p in required_props)
            if obj.type == 'MESH' and has_props:
                # 1. Link to the scene root temporarily
                bpy.context.collection.objects.link(obj)
                
                # 2. Synchronize Names
                obj.data.name = obj.name
                
                # 3. Find Target Armature
                arm_name = obj.get("sex")
                arm_obj = bpy.data.objects.get(arm_name)

                if arm_obj and arm_obj.type == 'ARMATURE':
                    # A. Handle Collections: Move mesh to armature's collections
                    # Remove from all current collections first
                    for col in obj.users_collection:
                        col.objects.unlink(obj)
                    
                    # Link to every collection the armature belongs to
                    for col in arm_obj.users_collection:
                        col.objects.link(obj)
                    
                    # B. Parent to Armature
                    obj.parent = arm_obj
                    
                    # C. Handle Armature Modifier
                    arm_mod = next((m for m in obj.modifiers if m.type == 'ARMATURE'), None)
                    if not arm_mod:
                        arm_mod = obj.modifiers.new(name="Armature", type='ARMATURE')
                    
                    arm_mod.object = arm_obj
                    print(f"Processed {obj.name}: Parented and Modset to {arm_name}")
                else:
                    print(f"Warning: Armature '{arm_name}' not found for {obj.name}")
            elif obj.type == 'MESH':
                # Object is a mesh but missing required properties - treat as helper/reference
                missing = [p for p in required_props if p not in obj.keys()]
                print(f"WARNING: Mesh object '{obj.name}' is missing required properties {missing}.")
                print(f"  Treating as helper/reference object (not a body part).")
                print(f"  Available properties: {[k for k in obj.keys() if not k.startswith('_')]}")
                # Don't remove - keep helper/reference objects in the scene
            else:
                # Clean up data not meeting criteria
                bpy.data.objects.remove(obj, do_unlink=True)

    # 4. Recursive Purge of all unlinked data (Materials, Textures, Meshes)
    bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)

    # Save
    bpy.ops.wm.save_as_mainfile(filepath=output_path)

if __name__ == "__main__":
    try:
        args = sys.argv[sys.argv.index("--") + 1:]
        if len(args) >= 2:
            *sources, output = args
            process_append(sources, output)
    except ValueError:
        print("Error: Use '--' to separate Blender args from script args.")

