#!/usr/bin/env python3
"""
Fix media URL configuration for production
This script updates the URLs configuration to properly serve media files
"""

import os
import sys
import shutil
from datetime import datetime

def fix_media_urls():
    """Fix the media URL configuration"""
    print("🔧 Fixing media URL configuration...")
    
    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}.backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
    shutil.copy2(urls_file, backup_file)
    print(f"📁 Created backup: {backup_file}")
    
    try:
        # Read current content
        with open(urls_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # New URLs configuration
        new_urls_content = '''"""
URL configuration for branch_system project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
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')),
]

# Media and static files configuration
if settings.DEBUG:
    # In development, serve both static and media files through Django
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
else:
    # In production, let the web server handle media files directly
    # Do NOT serve media files through Django in production
    pass

# 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: Updated URLs configuration")
        print("📝 Changes made:")
        print("   - Removed Django media file serving in production")
        print("   - Media files will now be served directly by web server")
        print("   - Kept Django serving for development mode")
        
        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 create_media_htaccess():
    """Create/update .htaccess for media directory"""
    print("\n📁 Creating/updating media .htaccess...")
    
    media_htaccess = 'media/.htaccess'
    
    htaccess_content = '''# HAVEN GRAZURI VESTMENT LIMITED- Media Files Configuration
# Serve media files directly through Apache/web server

# 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 media files
<FilesMatch "\\.(jpg|jpeg|png|gif|webp|pdf|doc|docx)$">
    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 media directory if it doesn't exist
        os.makedirs('media', exist_ok=True)
        
        with open(media_htaccess, 'w', encoding='utf-8') as f:
            f.write(htaccess_content)
        
        print(f"✅ SUCCESS: Created {media_htaccess}")
        return True
        
    except Exception as e:
        print(f"❌ ERROR: Failed to create .htaccess: {e}")
        return False

def test_media_configuration():
    """Test the media configuration"""
    print("\n🧪 Testing media configuration...")
    
    try:
        # Check if media directory exists
        if os.path.exists('media'):
            print("✅ Media directory exists")
            
            # Count files in media directory
            file_count = 0
            for root, dirs, files in os.walk('media'):
                file_count += len(files)
            
            print(f"📊 Found {file_count} files in media directory")
            
            # Check subdirectories
            subdirs = [
                'kyc/id_documents',
                'kyc/selfies',
                'kyc/utility_bills',
                'kyc/bank_statements',
                'profile_images'
            ]
            
            for subdir in subdirs:
                full_path = os.path.join('media', subdir)
                if os.path.exists(full_path):
                    files = [f for f in os.listdir(full_path) if os.path.isfile(os.path.join(full_path, f))]
                    print(f"   📁 {subdir}: {len(files)} files")
                else:
                    print(f"   ❌ {subdir}: directory missing")
        else:
            print("❌ Media directory doesn't exist")
            return False
        
        return True
        
    except Exception as e:
        print(f"❌ ERROR: {e}")
        return False

if __name__ == "__main__":
    print("🚀 MEDIA URL CONFIGURATION FIX STARTING...")
    print("=" * 60)
    
    # Fix URLs configuration
    success = fix_media_urls()
    
    if success:
        # Create media .htaccess
        htaccess_success = create_media_htaccess()
        
        # Test configuration
        test_success = test_media_configuration()
        
        print("\n" + "=" * 60)
        if success and htaccess_success and test_success:
            print("🎉 MEDIA URL FIX COMPLETED SUCCESSFULLY!")
            print("✅ URLs configuration updated")
            print("✅ Media .htaccess created")
            print("✅ Media directory structure verified")
            print("\n🔄 IMPORTANT: Restart your Django application!")
            print("   - In cPanel: Go to Python App → Restart")
            print("   - This is required for URL changes to take effect")
        else:
            print("⚠️ MEDIA URL FIX COMPLETED WITH ISSUES!")
            print("Some components may need manual attention")
    else:
        print("\n" + "=" * 60)
        print("❌ MEDIA URL FIX FAILED!")
        print("Please check the error messages above")
    
    print("\n📝 Next steps:")
    print("1. Restart your Django application in cPanel")
    print("2. Test image loading in the application")
    print("3. Verify media files are served directly by web server")
    print("4. Check browser developer tools for any remaining 404 errors")
    
    sys.exit(0 if success else 1)