#!/usr/bin/env python3
"""
Migrate image generation from OpenAI DALL-E to Grok API
This script updates existing image generation scripts to use Grok
"""

import os
import sys
import shutil
from datetime import datetime

def backup_file(filepath):
    """Create a backup of the original file"""
    backup_path = f"{filepath}.backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
    shutil.copy2(filepath, backup_path)
    print(f"📦 Backed up: {backup_path}")
    return backup_path

def update_openai_to_grok(filepath):
    """Update a Python file to use Grok instead of OpenAI"""
    
    with open(filepath, 'r') as f:
        content = f.read()
    
    original_content = content
    
    # Replace OpenAI imports and API calls
    replacements = [
        # API key environment variable
        ("OPENAI_API_KEY", "GROK_API_KEY"),
        ("os.getenv('OPENAI_API_KEY')", "os.getenv('GROK_API_KEY') or os.getenv('XAI_API_KEY')"),
        
        # API endpoints
        ("https://api.openai.com/v1/images/generations", "https://api.x.ai/v1/chat/completions"),
        ("api.openai.com", "api.x.ai"),
        
        # Model names
        ("'dall-e-3'", "'grok-2-vision-1212'"),
        ("'dall-e-2'", "'grok-2-vision-1212'"),
        ('"dall-e-3"', '"grok-2-vision-1212"'),
        ('"dall-e-2"', '"grok-2-vision-1212"'),
        
        # Comments and docstrings
        ("DALL-E 3", "Grok API"),
        ("DALL-E 2", "Grok API"),
        ("DALL-E", "Grok"),
        ("OpenAI", "Grok/xAI"),
    ]
    
    for old, new in replacements:
        content = content.replace(old, new)
    
    # Add Grok-specific import if needed
    if "import requests" in content and "GrokImageGenerator" not in content:
        # Add import for the Grok generator class
        import_line = "from generate_grok_image import GrokImageGenerator\n"
        
        # Find where to insert it (after other imports)
        lines = content.split('\n')
        import_index = 0
        for i, line in enumerate(lines):
            if line.startswith('import ') or line.startswith('from '):
                import_index = i + 1
        
        if import_index > 0:
            lines.insert(import_index, import_line)
            content = '\n'.join(lines)
    
    if content != original_content:
        with open(filepath, 'w') as f:
            f.write(content)
        return True
    
    return False

def find_image_generation_files():
    """Find all files that might use OpenAI for image generation"""
    
    base_path = '/var/www/twin-digital-media/public_html/_sites/cleankitchens'
    files_to_check = []
    
    # Search for Python files with OpenAI/DALL-E references
    for root, dirs, files in os.walk(base_path):
        # Skip certain directories
        skip_dirs = ['__pycache__', '.git', 'node_modules', 'vendor', 'lib']
        dirs[:] = [d for d in dirs if d not in skip_dirs]
        
        for file in files:
            if file.endswith('.py'):
                filepath = os.path.join(root, file)
                
                # Check if file contains OpenAI/DALL-E references
                try:
                    with open(filepath, 'r') as f:
                        content = f.read()
                        if any(term in content for term in ['openai', 'OPENAI', 'dall-e', 'DALL-E', 'dalle']):
                            files_to_check.append(filepath)
                except Exception:
                    pass
    
    return files_to_check

def main():
    """Main migration function"""
    
    print("🔄 Starting migration from OpenAI to Grok API...")
    print("-" * 50)
    
    # Check if Grok API key is set
    grok_key = os.getenv('GROK_API_KEY') or os.getenv('XAI_API_KEY')
    if not grok_key:
        print("⚠️ Warning: GROK_API_KEY or XAI_API_KEY not found in environment")
        print("Please set one of these environment variables before running the migrated scripts")
        print()
    
    # Find files to migrate
    print("🔍 Searching for files using OpenAI/DALL-E...")
    files = find_image_generation_files()
    
    if not files:
        print("✅ No files found using OpenAI/DALL-E")
        return
    
    print(f"📋 Found {len(files)} files to check:")
    for f in files:
        print(f"  - {f}")
    
    print()
    response = input("Do you want to migrate these files? (y/n): ")
    
    if response.lower() != 'y':
        print("❌ Migration cancelled")
        return
    
    # Migrate each file
    migrated = []
    for filepath in files:
        print(f"\n📝 Processing: {filepath}")
        
        # Skip the migration script itself and the Grok generator
        if 'migrate_to_grok' in filepath or 'generate_grok_image' in filepath:
            print("  ⏭️ Skipping (migration/grok file)")
            continue
        
        # Create backup
        backup_file(filepath)
        
        # Update the file
        if update_openai_to_grok(filepath):
            print("  ✅ Updated successfully")
            migrated.append(filepath)
        else:
            print("  ℹ️ No changes needed")
    
    print("\n" + "=" * 50)
    print(f"✅ Migration complete!")
    print(f"📊 Updated {len(migrated)} files")
    
    if migrated:
        print("\n📋 Updated files:")
        for f in migrated:
            print(f"  - {f}")
    
    print("\n⚠️ Important next steps:")
    print("1. Set the GROK_API_KEY or XAI_API_KEY environment variable")
    print("2. Test the migrated scripts to ensure they work correctly")
    print("3. Monitor the first few image generations for quality")
    
    # Create environment variable setup script
    env_script = """#!/bin/bash
# Set Grok API key for image generation
export GROK_API_KEY="your-grok-api-key-here"
# Alternative: export XAI_API_KEY="your-xai-api-key-here"

echo "✅ Grok API key set"
"""
    
    env_file = '/var/www/twin-digital-media/public_html/_sites/cleankitchens/production/scripts/set_grok_env.sh'
    with open(env_file, 'w') as f:
        f.write(env_script)
    os.chmod(env_file, 0o755)
    
    print(f"\n📝 Created environment setup script: {env_file}")
    print("   Edit this file with your API key and run: source set_grok_env.sh")

if __name__ == "__main__":
    main()