#!/usr/bin/env python3
"""
Fix Apache media serving configuration
Now that Django is no longer interfering, we need Apache to serve media files
"""

import os
import sys
from datetime import datetime

def create_apache_media_config():
    """Create proper Apache configuration for media serving"""
    print("🔧 Creating Apache media serving configuration...")
    
    # Main .htaccess with media serving rules
    main_htaccess_content = '''# HAVEN GRAZURI INVESTMENT LIMITED- Apache Configuration
RewriteEngine On

# Serve media files directly through Apache (bypass Django completely)
RewriteCond %{REQUEST_URI} ^/media/(.*)$
RewriteRule ^media/(.*)$ /media/$1 [L,QSA]

# Serve static files directly
RewriteCond %{REQUEST_URI} ^/static/(.*)$
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>

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

<Files "*.pyc">
    Order allow,deny
    Deny from all
</Files>
'''
    
    # Media directory .htaccess
    media_htaccess_content = '''# HAVEN GRAZURI VESTMENT LIMITED- Media Directory
# Direct Apache serving for all media files

# Enable directory access
Options +Indexes +FollowSymLinks

# Set proper MIME types for media files
<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
    AddType text/plain .txt
</IfModule>

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

# Set cache headers for better performance
<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 in media directory
<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 with Apache media serving rules")
        
        # Ensure media directory exists
        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 with direct serving configuration")
        
        return True
        
    except Exception as e:
        print(f"❌ Error creating Apache configuration: {e}")
        return False

def create_test_media_file():
    """Create a test media file to verify Apache serving"""
    print("\n🧪 Creating test media file...")
    
    try:
        # Create test directory
        test_dir = 'media/test'
        os.makedirs(test_dir, exist_ok=True)
        
        # Create test file
        test_file = os.path.join(test_dir, 'apache-test.txt')
        with open(test_file, 'w', encoding='utf-8') as f:
            f.write('Apache Media Serving Test\\n')
            f.write(f'Created: {datetime.now()}\\n')
            f.write('If you can see this file, Apache is serving media files correctly!\\n')
            f.write('\\n')
            f.write('This means your image files should also work now.\\n')
        
        print(f"✅ Created test file: {test_file}")
        print("🌐 Test URL: https://branchbusinessadvance.co.ke/media/test/apache-test.txt")
        
        return True
        
    except Exception as e:
        print(f"❌ Error creating test file: {e}")
        return False

def check_media_directory_structure():
    """Check and display media directory structure"""
    print("\n📁 Checking media directory structure...")
    
    try:
        if not os.path.exists('media'):
            print("❌ Media directory doesn't exist!")
            return False
        
        # Check if the specific file exists
        target_file = 'media/kyc/id_documents/FRONT-ID.jpeg'
        if os.path.exists(target_file):
            size = os.path.getsize(target_file)
            print(f"✅ Target file exists: {target_file} ({size} bytes)")
        else:
            print(f"❌ Target file missing: {target_file}")
            
            # Check if directory exists
            target_dir = 'media/kyc/id_documents'
            if os.path.exists(target_dir):
                files = os.listdir(target_dir)
                print(f"📁 Directory exists with {len(files)} files:")
                for file in files[:10]:  # Show first 10 files
                    print(f"   - {file}")
                if len(files) > 10:
                    print(f"   ... and {len(files) - 10} more files")
            else:
                print(f"❌ Directory missing: {target_dir}")
        
        # Check overall media structure
        total_files = 0
        for root, dirs, files in os.walk('media'):
            total_files += len(files)
        
        print(f"📊 Total files in media directory: {total_files}")
        
        return True
        
    except Exception as e:
        print(f"❌ Error checking media directory: {e}")
        return False

def check_file_permissions():
    """Check file permissions on media directory"""
    print("\n🔐 Checking file permissions...")
    
    try:
        media_dir = 'media'
        
        if os.path.exists(media_dir):
            # Check if directory is readable
            if os.access(media_dir, os.R_OK):
                print("✅ Media directory is readable")
            else:
                print("❌ Media directory is not readable")
                return False
            
            # Check if we can list directory contents
            try:
                files = os.listdir(media_dir)
                print(f"✅ Can list directory contents ({len(files)} items)")
            except PermissionError:
                print("❌ Cannot list directory contents - permission denied")
                return False
            
            # Check specific file if it exists
            target_file = 'media/kyc/id_documents/FRONT-ID.jpeg'
            if os.path.exists(target_file):
                if os.access(target_file, os.R_OK):
                    print("✅ Target file is readable")
                else:
                    print("❌ Target file is not readable")
                    return False
            
            return True
        else:
            print("❌ Media directory doesn't exist")
            return False
            
    except Exception as e:
        print(f"❌ Error checking permissions: {e}")
        return False

if __name__ == "__main__":
    print("🚀 FIXING APACHE MEDIA SERVING...")
    print("=" * 60)
    print("🎉 GREAT NEWS: Django is no longer interfering with media files!")
    print("Now we just need Apache to serve them directly.")
    print("=" * 60)
    
    # Create Apache configuration
    apache_success = create_apache_media_config()
    
    # Create test file
    test_success = create_test_media_file()
    
    # Check media directory
    media_check = check_media_directory_structure()
    
    # Check permissions
    permissions_ok = check_file_permissions()
    
    print("\\n" + "=" * 60)
    if apache_success and test_success:
        print("🎉 APACHE MEDIA SERVING CONFIGURATION COMPLETED!")
        print("✅ Apache .htaccess files created")
        print("✅ Media directory configured for direct serving")
        print("✅ Test file created for verification")
        
        if media_check and permissions_ok:
            print("✅ Media directory structure looks good")
            print("✅ File permissions are correct")
        else:
            print("⚠️ Some media directory issues detected")
        
        print("\\n🧪 TESTING STEPS:")
        print("1. First test: https://branchbusinessadvance.co.ke/media/test/apache-test.txt")
        print("   (This should show the test file content)")
        print("\\n2. Then test: https://branchbusinessadvance.co.ke/media/kyc/id_documents/FRONT-ID.jpeg")
        print("   (This should show your actual image)")
        
        print("\\n📝 What was configured:")
        print("   - Apache now serves media files directly")
        print("   - Proper MIME types for all file formats")
        print("   - Security headers and access controls")
        print("   - Performance optimizations (compression, caching)")
        
        print("\\n✨ NO APPLICATION RESTART NEEDED!")
        print("Apache configuration changes take effect immediately.")
        
    else:
        print("❌ APACHE CONFIGURATION FAILED!")
        print("Please check the error messages above")
    
    print("\\n🔍 If images still don't load:")
    print("1. Check that the files actually exist in the media directory")
    print("2. Verify file permissions are correct")
    print("3. Test the apache-test.txt file first")
    print("4. Check cPanel error logs for any Apache errors")
    
    sys.exit(0 if (apache_success and test_success) else 1)