#!/usr/bin/env python3
"""
Complete media serving fix - addresses all sources of the issue
This script will fix ALL places where Django media serving is configured
"""

import os
import sys
import shutil
from datetime import datetime

def complete_urls_fix():
    """Completely fix the URLs configuration"""
    print("🔧 Applying complete URLs fix...")
    
    urls_file = 'branch_system/urls.py'
    
    if not os.path.exists(urls_file):
        print(f"❌ ERROR: {urls_file} not found")
        return False
    
    # Create backup
    backup_file = f"{urls_file}.complete_fix_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
    shutil.copy2(urls_file, backup_file)
    print(f"📁 Created backup: {backup_file}")
    
    try:
        # Write completely new, clean URLs configuration
        new_urls_content = '''"""
URL configuration for branch_system project.
"""
from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from django.contrib.auth.decorators import login_required
from loans import views as loans_views

@login_required
@require_POST
def session_ping(request):
    return JsonResponse({'status': 'ok'})

@login_required
def home_redirect(request):
    return RedirectView.as_view(url='/dashboard/', permanent=False)(request)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home_redirect, name='home'),
    path('dashboard/', loans_views.dashboard, name='dashboard'),
    path('api/loan-data/', loans_views.api_loan_data, name='api_loan_data'),
    path('api/recent-activity/', loans_views.api_recent_activity, name='api_recent_activity'),
    path('api/session-ping/', session_ping, name='session_ping'),
    path('loans/', include('loans.urls')),
    path('', include('users.urls')),
    path('reports/', include('reports.urls')),
    path('utils/', include('utils.urls')),
]

# PRODUCTION MEDIA SERVING: DISABLED
# Media files are served directly by Apache/web server
# NO Django involvement in media file serving

# Customize admin site
admin.site.site_header = "HAVEN GRAZURI INVESTMENT LIMITED- Admin"
admin.site.site_title = "HAVEN GRAZURI Advance"
admin.site.index_title = "Welcome to HAVEN GRAZURI VESTMENT LIMITEDAdministration"
'''
        
        # Write the new content
        with open(urls_file, 'w', encoding='utf-8') as f:
            f.write(new_urls_content)
        
        print("✅ SUCCESS: Completely rewrote URLs configuration")
        print("📝 Changes made:")
        print("   - Removed ALL Django media serving")
        print("   - Removed ALL static() calls for media")
        print("   - Clean, production-ready configuration")
        
        return True
        
    except Exception as e:
        print(f"❌ ERROR: Failed to fix URLs: {e}")
        # Restore backup
        if os.path.exists(backup_file):
            shutil.copy2(backup_file, urls_file)
            print(f"🔄 Restored backup from {backup_file}")
        return False

def fix_utils_urls():
    """Fix utils/urls.py to remove any media serving"""
    print("\n🔧 Fixing utils/urls.py...")
    
    utils_urls_file = 'utils/urls.py'
    
    if not os.path.exists(utils_urls_file):
        print(f"❌ ERROR: {utils_urls_file} not found")
        return False
    
    try:
        # Read current content
        with open(utils_urls_file, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        
        # Remove any media-related lines
        new_lines = []
        removed_count = 0
        
        for line in lines:
            # Skip lines that contain media serving patterns
            if any(pattern in line for pattern in [
                "path('media/",
                "serve_media_file",
                "static(settings.MEDIA_URL"
            ]):
                removed_count += 1
                print(f"🗑️ Removing: {line.strip()}")
            else:
                new_lines.append(line)
        
        # Write cleaned content
        with open(utils_urls_file, 'w', encoding='utf-8') as f:
            f.writelines(new_lines)
        
        if removed_count > 0:
            print(f"✅ SUCCESS: Removed {removed_count} media serving lines from utils/urls.py")
        else:
            print("✅ SUCCESS: utils/urls.py already clean")
        
        return True
        
    except Exception as e:
        print(f"❌ ERROR: Failed to fix utils/urls.py: {e}")
        return False

def disable_media_middleware():
    """Disable the MediaFileMiddleware"""
    print("\n🔧 Disabling MediaFileMiddleware...")
    
    middleware_file = 'utils/middleware.py'
    
    if not os.path.exists(middleware_file):
        print(f"❌ ERROR: {middleware_file} not found")
        return False
    
    try:
        # Read current content
        with open(middleware_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Check if already disabled
        if 'MediaFileMiddleware_DISABLED' in content:
            print("✅ SUCCESS: MediaFileMiddleware already disabled")
            return True
        
        # Disable the middleware by replacing its __call__ method
        new_content = 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: Media files are now served by Apache/web server
        # No Django involvement in media file serving
        return self.get_response(request)'''
        )
        
        # Write updated content
        with open(middleware_file, 'w', encoding='utf-8') as f:
            f.write(new_content)
        
        print("✅ SUCCESS: MediaFileMiddleware disabled")
        return True
        
    except Exception as e:
        print(f"❌ ERROR: Failed to disable middleware: {e}")
        return False

def create_production_htaccess():
    """Create production .htaccess files"""
    print("\n📁 Creating production .htaccess files...")
    
    # Main .htaccess
    main_htaccess_content = '''# HAVEN GRAZURI VESTMENT LIMITED- Production Configuration
RewriteEngine On

# Serve media files directly - NO Django involvement
RewriteRule ^media/(.*)$ /media/$1 [L,QSA]

# Serve static files directly
RewriteRule ^static/(.*)$ /staticfiles/$1 [L,QSA]

# Security headers
<IfModule mod_headers.c>
    Header always set X-Content-Type-Options nosniff
    Header always set X-Frame-Options SAMEORIGIN
    Header always set X-XSS-Protection "1; mode=block"
</IfModule>
'''
    
    # Media .htaccess
    media_htaccess_content = '''# HAVEN GRAZURI VESTMENT LIMITED- Media Files
# Serve all media files directly through Apache

RewriteEngine On

# Set proper MIME types
<IfModule mod_mime.c>
    AddType image/jpeg .jpg .jpeg
    AddType image/png .png
    AddType image/gif .gif
    AddType image/webp .webp
    AddType application/pdf .pdf
</IfModule>

# Allow access to all media files
<FilesMatch "\\.(jpg|jpeg|png|gif|webp|pdf|doc|docx)$">
    Order allow,deny
    Allow from all
</FilesMatch>
'''
    
    try:
        # Create main .htaccess
        with open('.htaccess', 'w', encoding='utf-8') as f:
            f.write(main_htaccess_content)
        print("✅ Created main .htaccess")
        
        # Create media directory and .htaccess
        os.makedirs('media', exist_ok=True)
        with open('media/.htaccess', 'w', encoding='utf-8') as f:
            f.write(media_htaccess_content)
        print("✅ Created media/.htaccess")
        
        return True
        
    except Exception as e:
        print(f"❌ Error creating .htaccess files: {e}")
        return False

def verify_fix():
    """Verify that all fixes have been applied"""
    print("\n🔍 Verifying fixes...")
    
    issues = []
    
    # Check main URLs file
    try:
        with open('branch_system/urls.py', 'r', encoding='utf-8') as f:
            urls_content = f.read()
        
        if 'static(settings.MEDIA_URL' in urls_content:
            issues.append("branch_system/urls.py still contains media serving")
        else:
            print("✅ branch_system/urls.py: Clean")
    except Exception as e:
        issues.append(f"Could not check branch_system/urls.py: {e}")
    
    # Check utils URLs file
    try:
        with open('utils/urls.py', 'r', encoding='utf-8') as f:
            utils_urls_content = f.read()
        
        if "path('media/" in utils_urls_content:
            issues.append("utils/urls.py still contains media serving")
        else:
            print("✅ utils/urls.py: Clean")
    except Exception as e:
        issues.append(f"Could not check utils/urls.py: {e}")
    
    # Check middleware
    try:
        with open('utils/middleware.py', 'r', encoding='utf-8') as f:
            middleware_content = f.read()
        
        if "return self.serve_media_file(request)" in middleware_content:
            issues.append("utils/middleware.py still has active media serving")
        else:
            print("✅ utils/middleware.py: Disabled")
    except Exception as e:
        issues.append(f"Could not check utils/middleware.py: {e}")
    
    return issues

if __name__ == "__main__":
    print("🚀 COMPLETE MEDIA SERVING FIX...")
    print("=" * 70)
    
    # Apply all fixes
    urls_success = complete_urls_fix()
    utils_success = fix_utils_urls()
    middleware_success = disable_media_middleware()
    htaccess_success = create_production_htaccess()
    
    # Verify fixes
    issues = verify_fix()
    
    print("\\n" + "=" * 70)
    if urls_success and utils_success and middleware_success and htaccess_success and not issues:
        print("🎉 COMPLETE MEDIA FIX SUCCESSFUL!")
        print("✅ All Django media serving removed")
        print("✅ MediaFileMiddleware disabled")
        print("✅ Production .htaccess files created")
        print("✅ All verification checks passed")
        
        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("   - Completely removed Django media serving from URLs")
        print("   - Disabled MediaFileMiddleware")
        print("   - Created production .htaccess files")
        print("   - Apache will handle ALL media files directly")
        
        print("\\n🧪 After restart, the error should be completely gone!")
        
    else:
        print("❌ COMPLETE MEDIA FIX FAILED!")
        if issues:
            print("\\n⚠️ Issues found:")
            for issue in issues:
                print(f"   - {issue}")
        print("Please check the error messages above")
    
    print("\\n🌐 Test URL after restart:")
    print("   https://branchbusinessadvance.co.ke/media/kyc/id_documents/FRONT-ID.jpeg")
    
    sys.exit(0 if (urls_success and utils_success and middleware_success and htaccess_success and not issues) else 1)