#!/usr/bin/env python3
"""
Migration script to help users move from allSongs.json to songs.json
and update their configuration to use the new dynamic data directory.
"""

import os
import json
import shutil
from pathlib import Path

def load_json_file(file_path: str):
    """Load JSON file safely."""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        print(f"Error loading {file_path}: {e}")
        return None

def save_json_file(file_path: str, data):
    """Save JSON file safely."""
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
        return True
    except Exception as e:
        print(f"Error saving {file_path}: {e}")
        return False

def migrate_songs_file():
    """Migrate allSongs.json to songs.json if it exists."""
    old_file = 'data/allSongs.json'
    new_file = 'data/songs.json'
    
    if not os.path.exists(old_file):
        print(f"⚠️  {old_file} not found - no migration needed")
        return True
    
    if os.path.exists(new_file):
        print(f"⚠️  {new_file} already exists - skipping migration")
        return True
    
    print(f"🔄 Migrating {old_file} to {new_file}...")
    
    # Load the old file
    songs_data = load_json_file(old_file)
    if not songs_data:
        print(f"❌ Failed to load {old_file}")
        return False
    
    # Save to new file
    if save_json_file(new_file, songs_data):
        print(f"✅ Successfully migrated to {new_file}")
        
        # Create backup of old file
        backup_file = 'data/allSongs.json.backup'
        shutil.copy2(old_file, backup_file)
        print(f"📦 Created backup at {backup_file}")
        
        return True
    else:
        print(f"❌ Failed to save {new_file}")
        return False

def update_config():
    """Update config.json to include data_directory if not present."""
    config_file = 'config/config.json'
    
    if not os.path.exists(config_file):
        print(f"❌ {config_file} not found")
        return False
    
    print(f"🔄 Updating {config_file}...")
    
    # Load current config
    config = load_json_file(config_file)
    if not config:
        print(f"❌ Failed to load {config_file}")
        return False
    
    # Check if data_directory already exists
    if 'data_directory' in config:
        print(f"✅ data_directory already configured: {config['data_directory']}")
        return True
    
    # Add data_directory
    config['data_directory'] = 'data'
    
    # Create backup
    backup_file = 'config/config.json.backup'
    shutil.copy2(config_file, backup_file)
    print(f"📦 Created backup at {backup_file}")
    
    # Save updated config
    if save_json_file(config_file, config):
        print(f"✅ Successfully added data_directory to {config_file}")
        return True
    else:
        print(f"❌ Failed to save {config_file}")
        return False

def main():
    """Main migration function."""
    print("🎤 KaraokeMerge Migration Script")
    print("=" * 40)
    print("This script will help you migrate to the new configuration:")
    print("- Rename allSongs.json to songs.json")
    print("- Add data_directory to config.json")
    print()
    
    # Check if we're in the right directory
    if not os.path.exists('config') or not os.path.exists('data'):
        print("❌ Please run this script from the KaraokeMerge root directory")
        return False
    
    success = True
    
    # Migrate songs file
    if not migrate_songs_file():
        success = False
    
    # Update config
    if not update_config():
        success = False
    
    print()
    if success:
        print("✅ Migration completed successfully!")
        print()
        print("Next steps:")
        print("1. Test the CLI tool: python cli/main.py --show-config")
        print("2. Test the web UI: python start_web_ui.py")
        print("3. If everything works, you can delete the backup files")
    else:
        print("❌ Migration failed - please check the errors above")
        return False
    
    return True

if __name__ == "__main__":
    success = main()
    if not success:
        exit(1)
