#!/usr/bin/env python3
"""
Fix Media Files on Production Server
Run this script directly on the production server to fix media file serving issues
"""

import os
import sys
import django
from pathlib import Path

# Setup Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.conf import settings
from users.models import CustomUser
from django.db import connection

def clear_invalid_media_references():
    """Clear invalid media file references from database"""
    print("🗄️ Clearing invalid media file references from database...")
    
    cleared_count = 0
    users = CustomUser.objects.all()
    
    for user in users:
        # Check all document fields
        document_fields = [
            ('selfie', user.selfie),
            ('id_document', user.id_document),
            ('utility_bill', user.utility_bill),
            ('bank_statement', user.bank_statement),
            ('business_license', user.business_license),
            ('tax_certificate', user.tax_certificate),
            ('logbook', user.logbook),
            ('title_deed', user.title_deed),
            ('signature', user.signature),
            ('profile_image', user.profile_image),
        ]
        
        user_updated = False
        for field_name, field_value in document_fields:
            if field_value:
                file_path = os.path.join(settings.MEDIA_ROOT, field_value.name)
                if not os.path.exists(file_path):
                    print(f"❌ Clearing missing {field_name} for {user.get_full_name()}: {field_value.name}")
                    setattr(user, field_name, None)
                    user_updated = True
                    cleared_count += 1
        
        if user_updated:
            user.save()
    
    print(f"✅ Cleared {cleared_count} invalid media references")
    return cleared_count

def create_media_directories():
    """Create all required media directories"""
    print("📁 Creating media directories...")
    
    directories = [
        'media',
        'media/kyc',
        'media/kyc/selfies',
        'media/kyc/id_documents',
        'media/kyc/utility_bills',
        'media/kyc/bank_statements',
        'media/kyc/business_licenses',
        'media/kyc/tax_certificates',
        'media/kyc/logbooks',
        'media/kyc/title_deeds',
        'media/kyc/signatures',
        'media/profile_images',
        'media/receipts',
    ]
    
    for directory in directories:
        os.makedirs(directory, exist_ok=True)
        # Set proper permissions
        try:
            os.chmod(directory, 0o755)
        except:
            pass
        print(f"✅ Created/verified: {directory}")

def fix_media_permissions():
    """Fix media file and directory permissions"""
    print("🔒 Fixing media file permissions...")
    
    media_root = settings.MEDIA_ROOT
    if not os.path.exists(media_root):
        os.makedirs(media_root, exist_ok=True)
    
    # Set permissions for media directory and all subdirectories
    for root, dirs, files in os.walk(media_root):
        # Set directory permissions to 755
        try:
            os.chmod(root, 0o755)
        except:
            pass
        
        # Set file permissions to 644
        for file in files:
            file_path = os.path.join(root, file)
            try:
                os.chmod(file_path, 0o644)
            except:
                pass
    
    print("✅ Media permissions fixed")

def update_htaccess():
    """Update .htaccess to properly serve media files"""
    print("⚙️ Updating .htaccess for media file serving...")
    
    htaccess_content = """# Django Media Files Fix
RewriteEngine On

# Serve static files directly
RewriteCond %{REQUEST_URI} ^/static/
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*)$ - [L]

# Serve media files directly if they exist
RewriteCond %{REQUEST_URI} ^/media/
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*)$ - [L]

# Handle missing media files gracefully
RewriteCond %{REQUEST_URI} ^/media/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^media/(.*)$ /media_placeholder.html [L]

# Django application
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ passenger_wsgi.py/$1 [QSA,L]

# Security headers for media files
<FilesMatch "\\.(jpg|jpeg|png|gif|pdf|doc|docx)$">
    Header set Cache-Control "public, max-age=31536000"
    Header set X-Content-Type-Options "nosniff"
</FilesMatch>
"""
    
    try:
        with open('.htaccess', 'w') as f:
            f.write(htaccess_content)
        print("✅ Updated .htaccess")
    except Exception as e:
        print(f"❌ Failed to update .htaccess: {e}")

def create_media_placeholder():
    """Create a placeholder for missing media files"""
    print("🖼️ Creating media placeholder...")
    
    placeholder_content = """<!DOCTYPE html>
<html>
<head>
    <title>Media File Not Found</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
        .placeholder { background: #f0f0f0; padding: 20px; border-radius: 8px; }
    </style>
</head>
<body>
    <div class="placeholder">
        <h2>Media File Not Available</h2>
        <p>The requested media file could not be found.</p>
        <p>Please contact support if this issue persists.</p>
    </div>
</body>
</html>"""
    
    try:
        with open('media_placeholder.html', 'w') as f:
            f.write(placeholder_content)
        print("✅ Created media placeholder")
    except Exception as e:
        print(f"❌ Failed to create placeholder: {e}")

def create_default_avatar():
    """Create a default avatar for users without profile images"""
    print("👤 Creating default avatar...")
    
    # Create a simple SVG avatar
    svg_content = """<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
    <rect width="100" height="100" fill="#e5e7eb"/>
    <circle cx="50" cy="35" r="15" fill="#9ca3af"/>
    <ellipse cx="50" cy="75" rx="20" ry="15" fill="#9ca3af"/>
    <text x="50" y="95" text-anchor="middle" font-family="Arial" font-size="8" fill="#6b7280">No Image</text>
</svg>"""
    
    try:
        os.makedirs('media/profile_images', exist_ok=True)
        with open('media/profile_images/default_avatar.svg', 'w') as f:
            f.write(svg_content)
        print("✅ Created default avatar")
    except Exception as e:
        print(f"❌ Failed to create default avatar: {e}")

def test_media_access():
    """Test media file access"""
    print("🧪 Testing media file access...")
    
    test_file_path = 'media/test_access.txt'
    try:
        with open(test_file_path, 'w') as f:
            f.write('Media access test')
        
        if os.path.exists(test_file_path):
            with open(test_file_path, 'r') as f:
                content = f.read()
            
            os.remove(test_file_path)
            
            if content == 'Media access test':
                print("✅ Media file access test passed")
                return True
            else:
                print("❌ Media file access test failed - content mismatch")
                return False
        else:
            print("❌ Media file access test failed - file not created")
            return False
    except Exception as e:
        print(f"❌ Media file access test failed: {e}")
        return False

def update_settings_for_media():
    """Update Django settings for better media handling"""
    print("⚙️ Checking Django media settings...")
    
    print(f"MEDIA_ROOT: {settings.MEDIA_ROOT}")
    print(f"MEDIA_URL: {settings.MEDIA_URL}")
    
    # Check if media root exists
    if not os.path.exists(settings.MEDIA_ROOT):
        os.makedirs(settings.MEDIA_ROOT, exist_ok=True)
        print(f"✅ Created MEDIA_ROOT directory: {settings.MEDIA_ROOT}")
    else:
        print(f"✅ MEDIA_ROOT exists: {settings.MEDIA_ROOT}")

def main():
    """Main function to fix all media issues"""
    print("🔧 HAVEN GRAZURI INVESTMENT LIMITED- Media Files Fix")
    print("=" * 60)
    
    # Step 1: Create media directories
    create_media_directories()
    
    # Step 2: Fix permissions
    fix_media_permissions()
    
    # Step 3: Clear invalid database references
    cleared_count = clear_invalid_media_references()
    
    # Step 4: Update .htaccess
    update_htaccess()
    
    # Step 5: Create placeholder and default avatar
    create_media_placeholder()
    create_default_avatar()
    
    # Step 6: Check Django settings
    update_settings_for_media()
    
    # Step 7: Test media access
    test_passed = test_media_access()
    
    print("\n" + "=" * 60)
    print("🎉 Media files fix completed!")
    
    print(f"\n📊 SUMMARY:")
    print(f"   • Cleared {cleared_count} invalid media references from database")
    print(f"   • Created all required media directories")
    print(f"   • Fixed file and directory permissions")
    print(f"   • Updated .htaccess for proper media serving")
    print(f"   • Created placeholder and default avatar")
    print(f"   • Media access test: {'PASSED' if test_passed else 'FAILED'}")
    
    print(f"\n🎯 NEXT STEPS:")
    print("   1. Restart your web server/application")
    print("   2. Test the website - images should no longer show 404 errors")
    print("   3. Users without profile images will see default avatar")
    print("   4. Upload new documents to test file upload functionality")
    
    print(f"\n💡 NOTES:")
    print("   • Invalid database references have been cleared")
    print("   • Missing media files will show placeholder instead of 404")
    print("   • New file uploads should work normally")
    print("   • Users can re-upload their documents if needed")

if __name__ == "__main__":
    main()
