#!/usr/bin/env python3
"""
Emergency fix for media serving issues
This script will completely remove Django media serving in production
"""

import os
import sys
import shutil
from datetime import datetime

def emergency_fix_urls():
    """Emergency fix for URLs configuration"""
    print("🚨 EMERGENCY MEDIA FIX: Removing Django media serving...")
    
    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}.emergency_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
    shutil.copy2(urls_file, backup_file)
    print(f"📁 Created emergency backup: {backup_file}")
    
    try:
        # Completely new URLs configuration - minimal and clean
        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')),
]

# IMPORTANT: NO MEDIA SERVING THROUGH DJANGO IN PRODUCTION
# Media files are served directly by Apache/web server

# 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 removed Django media serving")
        return True
        
    except Exception as e:
        print(f"❌ ERROR: Failed to update 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 check_other_url_files():
    """Check other URL files that might be adding media serving"""
    print("\n🔍 Checking other URL files for media patterns...")
    
    url_files = [
        'users/urls.py',
        'loans/urls.py', 
        'reports/urls.py',
        'utils/urls.py'
    ]
    
    found_media_patterns = []
    
    for url_file in url_files:
        if os.path.exists(url_file):
            try:
                with open(url_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                
                # Check for media-related patterns
                if 'static(' in content and 'MEDIA' in content:
                    found_media_patterns.append(url_file)
                    print(f"⚠️ Found potential media pattern in: {url_file}")
                elif 'media/' in content.lower():
                    found_media_patterns.append(url_file)
                    print(f"⚠️ Found media reference in: {url_file}")
                else:
                    print(f"✅ Clean: {url_file}")
                    
            except Exception as e:
                print(f"❌ Error reading {url_file}: {e}")
        else:
            print(f"📄 Not found: {url_file}")
    
    return found_media_patterns

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

# Force HTTPS (uncomment if SSL is configured)
# RewriteCond %{HTTPS} off
# RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Serve media files directly - bypass Django completely
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"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

# Prevent access to sensitive files
<Files "*.py">
    Order allow,deny
    Deny from all
</Files>

<Files "*.pyc">
    Order allow,deny
    Deny from all
</Files>
'''
    
    # Media .htaccess
    media_htaccess_content = '''# HAVEN GRAZURI VESTMENT LIMITED- Media Files
# Serve all media files directly through Apache

# Enable rewrite engine
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
    AddType application/msword .doc
    AddType application/vnd.openxmlformats-officedocument.wordprocessingml.document .docx
</IfModule>

# Enable compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE image/jpeg
    AddOutputFilterByType DEFLATE image/png
    AddOutputFilterByType DEFLATE application/pdf
</IfModule>

# Set cache headers
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/webp "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
</IfModule>

# Security headers
<IfModule mod_headers.c>
    Header always set X-Content-Type-Options nosniff
    Header always set X-Frame-Options SAMEORIGIN
</IfModule>

# Allow access to all media files
<FilesMatch "\\.(jpg|jpeg|png|gif|webp|pdf|doc|docx|txt)$">
    Order allow,deny
    Allow from all
</FilesMatch>

# Prevent access to Python files
<Files "*.py">
    Order allow,deny
    Deny from all
</Files>

<Files "*.pyc">
    Order allow,deny
    Deny from all
</Files>
'''
    
    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 if it doesn't exist
        os.makedirs('media', exist_ok=True)
        
        # Create media .htaccess
        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 test_file_existence():
    """Test if the problematic file actually exists"""
    print("\n🧪 Testing file existence...")
    
    test_files = [
        'media/kyc/id_documents/FRONT-ID.jpeg',
        'media/kyc/id_documents/',
        'media/kyc/',
        'media/'
    ]
    
    for test_file in test_files:
        if os.path.exists(test_file):
            if os.path.isfile(test_file):
                size = os.path.getsize(test_file)
                print(f"✅ File exists: {test_file} ({size} bytes)")
            else:
                files = os.listdir(test_file) if os.path.isdir(test_file) else []
                print(f"📁 Directory exists: {test_file} ({len(files)} items)")
        else:
            print(f"❌ Not found: {test_file}")

if __name__ == "__main__":
    print("🚨 EMERGENCY MEDIA FIX STARTING...")
    print("=" * 70)
    
    # Fix URLs configuration
    urls_success = emergency_fix_urls()
    
    # Check other URL files
    media_patterns = check_other_url_files()
    
    # Create .htaccess files
    htaccess_success = create_production_htaccess()
    
    # Test file existence
    test_file_existence()
    
    print("\n" + "=" * 70)
    if urls_success and htaccess_success:
        print("🎉 EMERGENCY FIX COMPLETED!")
        print("✅ Django media serving completely removed")
        print("✅ Production .htaccess files created")
        print("✅ Web server will handle media files directly")
        
        if media_patterns:
            print(f"\n⚠️ WARNING: Found media patterns in {len(media_patterns)} files:")
            for pattern in media_patterns:
                print(f"   - {pattern}")
            print("These may need manual review.")
        
        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")
        
    else:
        print("❌ EMERGENCY FIX FAILED!")
        print("Please check the error messages above")
    
    print("\n📝 After restart, test this URL directly:")
    print("https://branchbusinessadvance.co.ke/media/kyc/id_documents/FRONT-ID.jpeg")
    
    sys.exit(0 if urls_success and htaccess_success else 1)