#!/usr/bin/env python3
"""
Safe deployment script for collation fixes
Includes backup and rollback capabilities
"""

import os
import sys
import subprocess
import datetime
import shutil
from pathlib import Path

def create_backup():
    """Create a database backup before making changes"""
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_dir = f"backup_collation_fix_{timestamp}"
    
    print(f"Creating backup in {backup_dir}...")
    
    try:
        os.makedirs(backup_dir, exist_ok=True)
        
        # Database backup command (adjust credentials as needed)
        backup_cmd = [
            "mysqldump",
            "-u", "acbptxvs",  # Replace with your username
            "-p",  # Will prompt for password
            "xygbfpsg_graz",  # Database name
            f"--result-file={backup_dir}/database_backup.sql"
        ]
        
        print("Running database backup...")
        result = subprocess.run(backup_cmd, capture_output=True, text=True)
        
        if result.returncode == 0:
            print(f"✓ Database backup created successfully in {backup_dir}/")
            return backup_dir
        else:
            print(f"✗ Backup failed: {result.stderr}")
            return None
            
    except Exception as e:
        print(f"✗ Backup error: {str(e)}")
        return None

def run_python_fix():
    """Run the Python collation fix script"""
    print("Running Python collation fix...")
    
    try:
        result = subprocess.run([
            sys.executable, "fix_collation_issues.py"
        ], capture_output=True, text=True)
        
        print("Python fix output:")
        print(result.stdout)
        
        if result.stderr:
            print("Errors/Warnings:")
            print(result.stderr)
            
        return result.returncode == 0
        
    except Exception as e:
        print(f"✗ Python fix error: {str(e)}")
        return False

def run_sql_fix():
    """Run the SQL collation fix as fallback"""
    print("Running SQL collation fix...")
    
    try:
        # You'll need to run this manually or adjust with your MySQL credentials
        print("Please run the following command manually:")
        print("mysql -u acbptxvs -p xygbfpsg_graz < fix_collation_sql.sql")
        
        input("Press Enter after running the SQL fix manually...")
        return True
        
    except Exception as e:
        print(f"✗ SQL fix error: {str(e)}")
        return False

def test_django_connection():
    """Test if Django can connect without collation errors"""
    print("Testing Django connection...")
    
    try:
        # Simple Django test
        test_script = """
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection
from loans.models import Loan
from users.models import CustomUser
from utils.models import Receipt

# Test basic queries
try:
    loan_count = Loan.objects.count()
    user_count = CustomUser.objects.count()
    receipt_count = Receipt.objects.count()
    print(f"✓ Connection test passed - Loans: {loan_count}, Users: {user_count}, Receipts: {receipt_count}")
except Exception as e:
    print(f"✗ Connection test failed: {str(e)}")
    exit(1)
"""
        
        with open("test_connection.py", "w") as f:
            f.write(test_script)
            
        result = subprocess.run([
            sys.executable, "test_connection.py"
        ], capture_output=True, text=True)
        
        print(result.stdout)
        if result.stderr:
            print("Errors:", result.stderr)
            
        # Cleanup
        os.remove("test_connection.py")
        
        return result.returncode == 0
        
    except Exception as e:
        print(f"✗ Connection test error: {str(e)}")
        return False

def main():
    """Main deployment function"""
    print("="*60)
    print("MYSQL COLLATION FIX DEPLOYMENT")
    print("="*60)
    
    # Step 1: Create backup
    print("\nStep 1: Creating backup...")
    backup_dir = create_backup()
    if not backup_dir:
        print("✗ Backup failed. Aborting deployment for safety.")
        sys.exit(1)
    
    # Step 2: Run Python fix
    print("\nStep 2: Running Python collation fix...")
    python_success = run_python_fix()
    
    if not python_success:
        print("Python fix had issues. Trying SQL fix...")
        sql_success = run_sql_fix()
        if not sql_success:
            print("✗ Both fixes failed. Check logs and backup.")
            sys.exit(1)
    
    # Step 3: Test connection
    print("\nStep 3: Testing Django connection...")
    if test_django_connection():
        print("✓ Collation fix deployed successfully!")
        print("✓ Django application should now work without collation errors")
        print(f"✓ Backup available at: {backup_dir}")
    else:
        print("✗ Connection test failed. You may need to restore from backup.")
        print(f"Backup location: {backup_dir}")
        sys.exit(1)
    
    print("\n" + "="*60)
    print("DEPLOYMENT COMPLETED SUCCESSFULLY")
    print("="*60)

if __name__ == "__main__":
    main()