import os
import json
import re

DETAILERS_DIR = 'data/detailers'

def migrate_detailers():
    if not os.path.exists(DETAILERS_DIR):
        print(f"Directory {DETAILERS_DIR} does not exist.")
        return

    count = 0
    for filename in os.listdir(DETAILERS_DIR):
        if filename.endswith('.json'):
            file_path = os.path.join(DETAILERS_DIR, filename)
            try:
                with open(file_path, 'r') as f:
                    data = json.load(f)
                
                # Create a new ordered dictionary
                new_data = {}
                
                # Copy existing fields up to 'prompt'
                if 'detailer_id' in data:
                    new_data['detailer_id'] = data['detailer_id']
                if 'detailer_name' in data:
                    new_data['detailer_name'] = data['detailer_name']
                
                # Handle 'prompt'
                prompt_val = data.get('prompt', [])
                if isinstance(prompt_val, str):
                    # Split by comma and strip whitespace
                    new_data['prompt'] = [p.strip() for p in prompt_val.split(',') if p.strip()]
                else:
                    new_data['prompt'] = prompt_val
                
                # Insert 'focus'
                if 'focus' not in data:
                    new_data['focus'] = ""
                else:
                    new_data['focus'] = data['focus']
                
                # Copy remaining fields
                for key, value in data.items():
                    if key not in ['detailer_id', 'detailer_name', 'prompt', 'focus']:
                        new_data[key] = value
                
                # Write back to file
                with open(file_path, 'w') as f:
                    json.dump(new_data, f, indent=2)
                
                print(f"Migrated {filename}")
                count += 1
                
            except Exception as e:
                print(f"Error processing {filename}: {e}")

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

if __name__ == '__main__':
    migrate_detailers()
