import bpy
import sys
import os

argv = sys.argv
argv = argv[argv.index("--") + 1:]

sys.path.insert(0, os.getcwd() + "/assets/blender/scripts")

source_filepath = argv[0]
armature_name = argv[1]

print("starting...")

def copy_actions_and_create_nla_tracks(source_filepath, target_object_name):
    """
    Copies actions from a source Blender file that do not exist in the current
    file, creates NLA tracks for them on a target object, and saves the file.

    Args:
        source_filepath (str): The full path to the source Blender file.
        target_object_name (str): The name of the object in the current file
                                  to which the actions and NLA tracks will be applied.
    """

    # 1. Link or Append Actions from the Source File
    with bpy.data.libraries.load(source_filepath, link=False) as (data_from, data_to):
        source_action_names = data_from.actions
        current_action_names = {action.name for action in bpy.data.actions}
        actions_to_append = [name for name in source_action_names if name not in current_action_names]
        data_to.actions = actions_to_append
        print(actions_to_append)

    # Get the target object
    target_object = bpy.data.objects.get(target_object_name)
    if not target_object:
        print(f"Error: Object '{target_object_name}' not found in the current file.")
        return

    # Ensure the object has an NLA editor
    if not target_object.animation_data:
        target_object.animation_data_create()

    # 2. Iterate through newly imported actions and create NLA tracks
    for action in data_to.actions:
        # Check if an action with the same name already exists in the current file
        # Add the action to the NLA editor as a strip
        nla_track = target_object.animation_data.nla_tracks.new()
        nla_track.name = f"NLA_Track_{action.name}"
        nla_track.strips.new(name=action.name, start=1, action=action)
        print(f"Created NLA track for action: {action.name}")

    # 3. Save the current Blender file
    bpy.ops.wm.save_as_mainfile(filepath=bpy.context.blend_data.filepath)
    print(f"File saved: {bpy.context.blend_data.filepath}")

# --- Usage Example ---
if __name__ == "__main__":
    # Replace with your actual source file path and target object name
    source_file = source_filepath
    target_obj = armature_name

    copy_actions_and_create_nla_tracks(source_file, target_obj)

