#!/usr/bin/env python3
"""
Emergency fix for missing media files
This script will:
1. Find all missing media files referenced in the database
2. Either copy from RuralPoint system or create placeholder files
3. Update the media serving to handle missing files gracefully
"""

import os
import sys
import django
from pathlib import Path
import shutil

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

from users.models import CustomUser

def copy_missing_files_from_ruralpoint():
    """Copy missing files from RuralPoint system"""
    print("🔍 Checking for missing media files...")
    
    branch_media = Path('media')
    rural_media = Path('RuralPoint/media')
    
    missing_files = []
    copied_files = []
    
    # Check all users for missing files
    for user in CustomUser.objects.all():
        file_fields = [
            ('id_document', user.id_document),
            ('selfie', user.selfie),
            ('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),
        ]
        
        for field_name, file_path in file_fields:
            if file_path:
                branch_file = branch_media / file_path
                rural_file = rural_media / file_path
                
                if not branch_file.exists():
                    missing_files.append((user.username, field_name, file_path))
                    
                    # Try to copy from RuralPoint
                    if rural_file.exists():
                        # Ensure directory exists
                        branch_file.parent.mkdir(parents=True, exist_ok=True)
                        shutil.copy2(rural_file, branch_file)
                        copied_files.append(file_path)
                        print(f"✅ Copied: {file_path}")
                    else:
                        print(f"❌ Missing in both systems: {file_path}")
    
    print(f"\n📊 Summary:")
    print(f"Missing files found: {len(missing_files)}")
    print(f"Files copied from RuralPoint: {len(copied_files)}")
    
    return missing_files, copied_files

def create_placeholder_files():
    """Create placeholder files for missing media"""
    print("\n🎨 Creating placeholder files...")
    
    # Create a simple placeholder image
    placeholder_content = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\tpHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x12IDATx\x9cc```bPPP\x00\x02\xac\xea\x05\x1b\x00\x00\x00\x00IEND\xaeB`\x82'
    
    missing_files, _ = copy_missing_files_from_ruralpoint()
    
    for username, field_name, file_path in missing_files:
        file_full_path = Path('media') / file_path
        
        if not file_full_path.exists():
            # Ensure directory exists
            file_full_path.parent.mkdir(parents=True, exist_ok=True)
            
            # Create placeholder based on file extension
            if file_path.lower().endswith(('.jpg', '.jpeg', '.png')):
                with open(file_full_path, 'wb') as f:
                    f.write(placeholder_content)
                print(f"📄 Created placeholder image: {file_path}")
            elif file_path.lower().endswith('.pdf'):
                # Simple PDF placeholder
                pdf_content = b'%PDF-1.4\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\nxref\n0 4\n0000000000 65535 f \n0000000009 00000 n \n0000000058 00000 n \n0000000115 00000 n \ntrailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n174\n%%EOF'
                with open(file_full_path, 'wb') as f:
                    f.write(pdf_content)
                print(f"📄 Created placeholder PDF: {file_path}")

def update_media_middleware():
    """Update middleware to handle missing files gracefully"""
    print("\n🔧 Updating media middleware...")
    
    middleware_path = Path('utils/middleware.py')
    
    # Read current middleware
    with open(middleware_path, 'r') as f:
        content = f.read()
    
    # Check if MediaFileMiddleware already handles missing files
    if 'placeholder' not in content:
        # Add placeholder handling to MediaFileMiddleware
        new_middleware = '''
class MediaFileMiddleware:
    """Middleware to serve media files with fallback for missing files"""
    
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.path.startswith('/media/'):
            return self.serve_media_file(request)
        return self.get_response(request)

    def serve_media_file(self, request):
        from django.http import FileResponse, Http404, HttpResponse
        from django.conf import settings
        import os
        
        # Get the file path
        file_path = request.path[7:]  # Remove '/media/'
        full_path = os.path.join(settings.MEDIA_ROOT, file_path)
        
        # If file exists, serve it
        if os.path.exists(full_path):
            try:
                return FileResponse(open(full_path, 'rb'))
            except IOError:
                pass
        
        # File doesn't exist, create a placeholder response
        if file_path.lower().endswith(('.jpg', '.jpeg', '.png')):
            # Return a 1x1 transparent PNG
            placeholder_content = b'\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x01\\x08\\x02\\x00\\x00\\x00\\x90wS\\xde\\x00\\x00\\x00\\tpHYs\\x00\\x00\\x0b\\x13\\x00\\x00\\x0b\\x13\\x01\\x00\\x9a\\x9c\\x18\\x00\\x00\\x00\\x12IDATx\\x9cc```bPPP\\x00\\x02\\xac\\xea\\x05\\x1b\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82'
            response = HttpResponse(placeholder_content, content_type='image/png')
            response['Cache-Control'] = 'no-cache'
            return response
        
        # For other files, return 404
        raise Http404(f"Media file not found: {file_path}")
'''
        
        # Replace the existing MediaFileMiddleware class
        import re
        pattern = r'class MediaFileMiddleware:.*?(?=class|\Z)'
        content = re.sub(pattern, new_middleware.strip(), content, flags=re.DOTALL)
        
        with open(middleware_path, 'w') as f:
            f.write(content)
        
        print("✅ Updated MediaFileMiddleware to handle missing files")

def main():
    print("🚀 Starting emergency media files fix...")
    
    try:
        # Step 1: Copy missing files from RuralPoint
        copy_missing_files_from_ruralpoint()
        
        # Step 2: Create placeholders for still missing files
        create_placeholder_files()
        
        # Step 3: Update middleware for graceful handling
        update_media_middleware()
        
        print("\n✅ Emergency fix completed!")
        print("🔄 Please restart your Django application for middleware changes to take effect.")
        
    except Exception as e:
        print(f"❌ Error during fix: {e}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    main()