#!/usr/bin/env python3
"""
Emergency Rollback Script for Branch Filtering Deployment
Use this script if issues occur after deployment
"""

import os
import sys
import shutil
import subprocess
from datetime import datetime

def log_message(message, level='INFO'):
    """Log messages with timestamp"""
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(f"[{timestamp}] {level}: {message}")

def find_backup_directory():
    """Find the most recent backup directory"""
    try:
        current_dir = os.getcwd()
        parent_dir = os.path.dirname(current_dir)
        
        # Look for backup directories
        backup_dirs = []
        for item in os.listdir(parent_dir):
            if item.startswith('backup_') and os.path.isdir(os.path.join(parent_dir, item)):
                backup_dirs.append(item)
        
        if not backup_dirs:
            log_message("❌ No backup directories found", 'ERROR')
            return None
        
        # Sort by name (which includes timestamp) to get the most recent
        backup_dirs.sort(reverse=True)
        most_recent = backup_dirs[0]
        
        backup_path = os.path.join(parent_dir, most_recent)
        log_message(f"Found most recent backup: {backup_path}")
        return backup_path
        
    except Exception as e:
        log_message(f"❌ Error finding backup directory: {e}", 'ERROR')
        return None

def stop_web_services():
    """Stop web services"""
    log_message("Stopping web services...")
    
    services = ['apache2', 'nginx', 'gunicorn']
    stopped_services = []
    
    for service in services:
        try:
            result = subprocess.run(['sudo', 'systemctl', 'stop', service], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                log_message(f"✅ Stopped {service}")
                stopped_services.append(service)
            else:
                log_message(f"ℹ️  {service} not running or not found")
        except Exception as e:
            log_message(f"⚠️  Could not stop {service}: {e}")
    
    return stopped_services

def start_web_services(services):
    """Start web services"""
    log_message("Starting web services...")
    
    for service in services:
        try:
            result = subprocess.run(['sudo', 'systemctl', 'start', service], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                log_message(f"✅ Started {service}")
            else:
                log_message(f"❌ Failed to start {service}", 'ERROR')
        except Exception as e:
            log_message(f"❌ Error starting {service}: {e}", 'ERROR')

def backup_current_state():
    """Backup current state before rollback"""
    try:
        current_dir = os.getcwd()
        parent_dir = os.path.dirname(current_dir)
        
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        rollback_backup = os.path.join(parent_dir, f'pre_rollback_backup_{timestamp}')
        
        log_message(f"Creating pre-rollback backup: {rollback_backup}")
        shutil.copytree(current_dir, rollback_backup)
        log_message("✅ Pre-rollback backup created")
        return rollback_backup
        
    except Exception as e:
        log_message(f"❌ Failed to create pre-rollback backup: {e}", 'ERROR')
        return None

def restore_from_backup(backup_path):
    """Restore code from backup"""
    try:
        current_dir = os.getcwd()
        parent_dir = os.path.dirname(current_dir)
        
        log_message(f"Restoring from backup: {backup_path}")
        
        # Remove current directory
        os.chdir(parent_dir)
        shutil.rmtree(os.path.basename(current_dir))
        
        # Restore from backup
        shutil.copytree(backup_path, os.path.basename(current_dir))
        
        # Change back to restored directory
        os.chdir(os.path.basename(current_dir))
        
        log_message("✅ Code restored from backup")
        return True
        
    except Exception as e:
        log_message(f"❌ Failed to restore from backup: {e}", 'ERROR')
        return False

def verify_rollback():
    """Verify rollback was successful"""
    log_message("Verifying rollback...")
    
    try:
        # Try to import Django and basic models
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')
        
        try:
            import django
            django.setup()
            
            from django.db import connection
            from users.models import Branch, CustomUser
            
            # Test database connection
            with connection.cursor() as cursor:
                cursor.execute("SELECT COUNT(*) FROM users_branch")
                branch_count = cursor.fetchone()[0]
                
            log_message(f"✅ Database connection working (found {branch_count} branches)")
            
            # Test basic model access
            user_count = CustomUser.objects.count()
            log_message(f"✅ Model access working (found {user_count} users)")
            
            return True
            
        except Exception as e:
            log_message(f"❌ Django/Database verification failed: {e}", 'ERROR')
            return False
            
    except Exception as e:
        log_message(f"❌ Rollback verification failed: {e}", 'ERROR')
        return False

def create_rollback_report():
    """Create rollback report"""
    try:
        report_content = f"""
# Branch Filtering Rollback Report
Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

## Rollback Status: ✅ COMPLETED

## Actions Taken:
1. ✅ Web services stopped
2. ✅ Pre-rollback backup created
3. ✅ Code restored from backup
4. ✅ Web services restarted
5. ✅ System verification completed

## Rollback Reason:
[Please document the reason for rollback]

## System Status After Rollback:
- ✅ Database connection: Working
- ✅ Model access: Working
- ✅ Web services: Running

## Next Steps:
1. Investigate the issues that caused the rollback
2. Fix the problems in development environment
3. Test thoroughly before next deployment attempt
4. Update deployment procedures if necessary

## Contact Information:
- Rollback performed by: [Name]
- Date/Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
- Backup used: [Backup directory name]

Rollback completed successfully.
"""
        
        with open('rollback_report.md', 'w') as f:
            f.write(report_content)
        
        log_message("✅ Rollback report created: rollback_report.md")
        return True
        
    except Exception as e:
        log_message(f"❌ Failed to create rollback report: {e}", 'ERROR')
        return False

def emergency_rollback():
    """Perform emergency rollback"""
    log_message("="*60)
    log_message("EMERGENCY ROLLBACK - BRANCH FILTERING DEPLOYMENT")
    log_message("="*60)
    
    # Confirm rollback
    print("\n⚠️  WARNING: This will rollback the branch filtering deployment!")
    print("This action will:")
    print("1. Stop web services")
    print("2. Restore code from the most recent backup")
    print("3. Restart web services")
    print("4. Verify system functionality")
    
    confirm = input("\nAre you sure you want to proceed? (yes/no): ").lower().strip()
    if confirm != 'yes':
        log_message("Rollback cancelled by user")
        return False
    
    # Step 1: Find backup
    log_message("\n1. Finding backup directory...")
    backup_path = find_backup_directory()
    if not backup_path:
        log_message("❌ Cannot proceed without backup", 'ERROR')
        return False
    
    # Step 2: Stop services
    log_message("\n2. Stopping web services...")
    stopped_services = stop_web_services()
    
    # Step 3: Backup current state
    log_message("\n3. Creating pre-rollback backup...")
    pre_rollback_backup = backup_current_state()
    
    # Step 4: Restore from backup
    log_message("\n4. Restoring from backup...")
    restore_success = restore_from_backup(backup_path)
    if not restore_success:
        log_message("❌ Rollback failed during restore", 'ERROR')
        return False
    
    # Step 5: Start services
    log_message("\n5. Starting web services...")
    start_web_services(stopped_services)
    
    # Step 6: Verify rollback
    log_message("\n6. Verifying rollback...")
    verify_success = verify_rollback()
    
    # Step 7: Create report
    log_message("\n7. Creating rollback report...")
    create_rollback_report()
    
    # Summary
    log_message("\n" + "="*60)
    log_message("ROLLBACK SUMMARY")
    log_message("="*60)
    
    if restore_success and verify_success:
        log_message("✅ ROLLBACK SUCCESSFUL!")
        log_message("System has been restored to previous working state.")
        log_message(f"Pre-rollback backup saved: {pre_rollback_backup}")
        return True
    else:
        log_message("❌ ROLLBACK INCOMPLETE!")
        log_message("Manual intervention may be required.")
        return False

if __name__ == '__main__':
    try:
        success = emergency_rollback()
        sys.exit(0 if success else 1)
    except KeyboardInterrupt:
        log_message("\nRollback cancelled by user", 'WARNING')
        sys.exit(1)
    except Exception as e:
        log_message(f"❌ Rollback script crashed: {e}", 'ERROR')
        sys.exit(1)