#!/usr/bin/env python3
"""
Migration script to move .env to persistent directories as mbetterd.conf
"""
import os
import shutil
from pathlib import Path

def migrate_config():
    """Migrate .env file to persistent directories as mbetterd.conf"""
    
    # Import persistent directory utilities
    try:
        from app.utils.directories import get_persistent_directories, setup_persistent_directories
        directories = setup_persistent_directories()
        config_dir = directories['config']
        
        print(f"Using persistent config directory: {config_dir}")
        
        # Check if .env file exists
        env_file = Path('.env')
        if not env_file.exists():
            print("No .env file found to migrate")
            return False
        
        # Create mbetterd.conf path
        conf_file = Path(config_dir) / 'mbetterd.conf'
        
        # Create config directory if it doesn't exist
        os.makedirs(config_dir, exist_ok=True)
        
        # Copy .env to mbetterd.conf
        print(f"Copying {env_file} to {conf_file}")
        shutil.copy2(env_file, conf_file)
        
        # Add header to conf file
        with open(conf_file, 'r') as f:
            content = f.read()
        
        header = """# MBetter Daemon Configuration
# This file contains configuration settings for the MBetter daemon
# Format: KEY=VALUE (one per line)
# Lines starting with # are comments

"""
        
        with open(conf_file, 'w') as f:
            f.write(header + content)
        
        print(f"Successfully migrated configuration to {conf_file}")
        print(f"Original .env file preserved at {env_file}")
        
        return True
        
    except Exception as e:
        print(f"Error migrating configuration: {str(e)}")
        return False

if __name__ == '__main__':
    success = migrate_config()
    if success:
        print("\nConfiguration migration completed successfully!")
        print("The application will now use mbetterd.conf from persistent directories.")
        print("You can safely remove the .env file if desired.")
    else:
        print("\nConfiguration migration failed!")
        print("The application will continue to use the .env file.")