import os
import json
from collections import OrderedDict

ACTIONS_DIR = 'data/actions'

def migrate_actions():
    if not os.path.exists(ACTIONS_DIR):
        print(f"Directory {ACTIONS_DIR} not found.")
        return

    count = 0
    for filename in os.listdir(ACTIONS_DIR):
        if not filename.endswith('.json'):
            continue
            
        filepath = os.path.join(ACTIONS_DIR, filename)
        try:
            with open(filepath, 'r') as f:
                data = json.load(f, object_pairs_hook=OrderedDict)
            
            # Check if participants already exists
            if 'participants' in data:
                print(f"Skipping {filename}: 'participants' already exists.")
                continue
                
            # Create new ordered dict to enforce order
            new_data = OrderedDict()
            
            # Copy keys up to 'action'
            found_action = False
            for key, value in data.items():
                new_data[key] = value
                if key == 'action':
                    found_action = True
                    # Insert participants here
                    new_data['participants'] = {
                        "solo_focus": "true",
                        "orientation": "MF"
                    }
            
            # If 'action' wasn't found, append at the end
            if not found_action:
                print(f"Warning: 'action' key not found in {filename}. Appending 'participants' at the end.")
                new_data['participants'] = {
                    "solo_focus": "true",
                    "orientation": "MF"
                }
            
            # Write back to file
            with open(filepath, 'w') as f:
                json.dump(new_data, f, indent=2)
                
            count += 1
            # print(f"Updated {filename}") # Commented out to reduce noise if many files
            
        except Exception as e:
            print(f"Error processing {filename}: {e}")

    print(f"Migration complete. Updated {count} files.")

if __name__ == "__main__":
    migrate_actions()
