#!/usr/bin/env python3
"""
Fix the media middleware issue
This script disables the MediaFileMiddleware that's causing 404 errors
"""

import os
import sys
import shutil
from datetime import datetime

def fix_media_middleware():
    """Fix the media middleware by disabling it"""
    print("🔧 Fixing MediaFileMiddleware in utils/middleware.py...")
    
    middleware_file = 'utils/middleware.py'
    
    if not os.path.exists(middleware_file):
        print(f"❌ ERROR: {middleware_file} not found")
        return False
    
    # Create backup
    backup_file = f"{middleware_file}.backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
    shutil.copy2(middleware_file, backup_file)
    print(f"📁 Created backup: {backup_file}")
    
    try:
        # Read current content
        with open(middleware_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Replace the MediaFileMiddleware to make it inactive
        new_content = content.replace(
            'class MediaFileMiddleware:',
            'class MediaFileMiddleware_DISABLED:'
        ).replace(
            'def __call__(self, request):',
            'def __call__(self, request):'
        )
        
        # Also replace the middleware call logic to bypass media serving
        new_content = new_content.replace(
            '''    def __call__(self, request):
        # Check if this is a media file request
        if request.path.startswith('/media/'):
            return self.serve_media_file(request)
        
        return self.get_response(request)''',
            '''    def __call__(self, request):
        # DISABLED: Let web server handle media files directly
        # Media file serving is now handled by Apache/web server
        return self.get_response(request)'''
        )
        
        # Write the updated content
        with open(middleware_file, 'w', encoding='utf-8') as f:
            f.write(new_content)
        
        print("✅ SUCCESS: Disabled MediaFileMiddleware")
        print("📝 Changes made:")
        print("   - Renamed class to MediaFileMiddleware_DISABLED")
        print("   - Disabled media file interception")
        print("   - Media files will now be served by web server")
        
        return True
        
    except Exception as e:
        print(f"❌ ERROR: Failed to fix middleware: {e}")
        # Restore backup
        if os.path.exists(backup_file):
            shutil.copy2(backup_file, middleware_file)
            print(f"🔄 Restored backup from {backup_file}")
        return False

def check_settings_middleware():
    """Check if the middleware is registered in settings"""
    print("\n🔍 Checking middleware configuration in settings...")
    
    settings_files = [
        'branch_system/settings.py',
        'branch_system/settings_production.py'
    ]
    
    found_middleware = []
    
    for settings_file in settings_files:
        if os.path.exists(settings_file):
            try:
                with open(settings_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                
                if 'MediaFileMiddleware' in content:
                    found_middleware.append(settings_file)
                    print(f"⚠️ Found MediaFileMiddleware in: {settings_file}")
                    
                    # Show the relevant lines
                    lines = content.split('\\n')
                    for i, line in enumerate(lines, 1):
                        if 'MediaFileMiddleware' in line:
                            print(f"   Line {i}: {line.strip()}")
                else:
                    print(f"✅ No MediaFileMiddleware found in: {settings_file}")
                    
            except Exception as e:
                print(f"❌ Error reading {settings_file}: {e}")
        else:
            print(f"📄 Not found: {settings_file}")
    
    return found_middleware

def fix_settings_middleware():
    """Remove MediaFileMiddleware from settings if present"""
    print("\n🔧 Removing MediaFileMiddleware from settings...")
    
    settings_files = [
        'branch_system/settings.py',
        'branch_system/settings_production.py'
    ]
    
    fixed_files = []
    
    for settings_file in settings_files:
        if os.path.exists(settings_file):
            try:
                with open(settings_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                
                if 'MediaFileMiddleware' in content:
                    # Create backup
                    backup_file = f"{settings_file}.backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
                    shutil.copy2(settings_file, backup_file)
                    print(f"📁 Created backup: {backup_file}")
                    
                    # Remove or comment out the middleware
                    new_content = content.replace(
                        "'utils.middleware.MediaFileMiddleware',",
                        "# 'utils.middleware.MediaFileMiddleware',  # DISABLED - Let web server handle media"
                    ).replace(
                        '"utils.middleware.MediaFileMiddleware",',
                        '# "utils.middleware.MediaFileMiddleware",  # DISABLED - Let web server handle media'
                    )
                    
                    # Write updated content
                    with open(settings_file, 'w', encoding='utf-8') as f:
                        f.write(new_content)
                    
                    fixed_files.append(settings_file)
                    print(f"✅ Disabled MediaFileMiddleware in: {settings_file}")
                    
            except Exception as e:
                print(f"❌ Error fixing {settings_file}: {e}")
    
    return fixed_files

if __name__ == "__main__":
    print("🚀 FIXING MEDIA MIDDLEWARE ISSUE...")
    print("=" * 60)
    
    # Fix the middleware class
    middleware_success = fix_media_middleware()
    
    # Check settings
    middleware_in_settings = check_settings_middleware()
    
    # Fix settings if needed
    fixed_settings = []
    if middleware_in_settings:
        fixed_settings = fix_settings_middleware()
    
    print("\\n" + "=" * 60)
    if middleware_success:
        print("🎉 MEDIA MIDDLEWARE FIX COMPLETED!")
        print("✅ MediaFileMiddleware disabled in utils/middleware.py")
        
        if fixed_settings:
            print(f"✅ MediaFileMiddleware disabled in {len(fixed_settings)} settings files")
        elif middleware_in_settings:
            print("⚠️ MediaFileMiddleware found in settings but not disabled")
        else:
            print("✅ MediaFileMiddleware not found in settings")
        
        print("\\n🔄 CRITICAL: RESTART YOUR DJANGO APPLICATION!")
        print("   1. Go to cPanel → Python App")
        print("   2. Click 'Restart' for HAVEN GRAZURI Advance")
        print("   3. Wait for restart to complete")
        print("   4. Test image loading")
        
        print("\\n📝 What was fixed:")
        print("   - MediaFileMiddleware no longer intercepts media requests")
        print("   - Apache/web server will handle media files directly")
        print("   - No more Django involvement in media serving")
        
    else:
        print("❌ MEDIA MIDDLEWARE FIX FAILED!")
        print("Please check the error messages above")
    
    print("\\n🧪 After restart, test:")
    print("   https://branchbusinessadvance.co.ke/media/kyc/id_documents/FRONT-ID.jpeg")
    
    sys.exit(0 if middleware_success else 1)