#!/usr/bin/env python3
"""
Fix the media serving issue in utils/urls.py
This script removes the problematic media serving line
"""

import os
import sys
import shutil
from datetime import datetime

def fix_utils_urls():
    """Fix the utils/urls.py file to remove media serving"""
    print("🔧 Fixing utils/urls.py to remove media serving...")
    
    utils_urls_file = 'utils/urls.py'
    
    if not os.path.exists(utils_urls_file):
        print(f"❌ ERROR: {utils_urls_file} not found")
        return False
    
    # Create backup
    backup_file = f"{utils_urls_file}.backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
    shutil.copy2(utils_urls_file, backup_file)
    print(f"📁 Created backup: {backup_file}")
    
    try:
        # Read current content
        with open(utils_urls_file, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        
        # Remove the problematic media serving line
        new_lines = []
        removed_lines = []
        
        for line in lines:
            # Skip lines that contain media serving patterns
            if "path('media/" in line or "serve_media_file" in line:
                removed_lines.append(line.strip())
                print(f"🗑️ Removing line: {line.strip()}")
            else:
                new_lines.append(line)
        
        # Write the cleaned content
        with open(utils_urls_file, 'w', encoding='utf-8') as f:
            f.writelines(new_lines)
        
        print(f"✅ SUCCESS: Removed {len(removed_lines)} problematic lines")
        for line in removed_lines:
            print(f"   - {line}")
        
        return True
        
    except Exception as e:
        print(f"❌ ERROR: Failed to fix utils/urls.py: {e}")
        # Restore backup
        if os.path.exists(backup_file):
            shutil.copy2(backup_file, utils_urls_file)
            print(f"🔄 Restored backup from {backup_file}")
        return False

def check_all_url_files():
    """Check all URL files for media serving patterns"""
    print("\n🔍 Checking all URL files for media serving patterns...")
    
    url_files = [
        'branch_system/urls.py',
        'users/urls.py',
        'loans/urls.py',
        'reports/urls.py',
        'utils/urls.py'
    ]
    
    found_issues = []
    
    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 serving patterns
                issues = []
                lines = content.split('\\n')
                
                for i, line in enumerate(lines, 1):
                    if any(pattern in line for pattern in [
                        "path('media/",
                        "static(settings.MEDIA_URL",
                        "serve_media_file",
                        "django.views.static.serve"
                    ]):
                        issues.append(f"Line {i}: {line.strip()}")
                
                if issues:
                    found_issues.append((url_file, issues))
                    print(f"⚠️ Issues found in {url_file}:")
                    for issue in issues:
                        print(f"   {issue}")
                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_issues

def create_media_test_file():
    """Create a test file to verify media serving works"""
    print("\n🧪 Creating media test file...")
    
    try:
        # Create test directories
        test_dir = 'media/test'
        os.makedirs(test_dir, exist_ok=True)
        
        # Create test file
        test_file = os.path.join(test_dir, 'test.txt')
        with open(test_file, 'w') as f:
            f.write('Media serving test file\\n')
            f.write(f'Created: {datetime.now()}\\n')
            f.write('If you can see this, media serving is working!\\n')
        
        print(f"✅ Created test file: {test_file}")
        print("🌐 Test URL: https://branchbusinessadvance.co.ke/media/test/test.txt")
        
        return True
        
    except Exception as e:
        print(f"❌ Error creating test file: {e}")
        return False

if __name__ == "__main__":
    print("🚀 FIXING UTILS MEDIA SERVING ISSUE...")
    print("=" * 60)
    
    # Fix utils/urls.py
    utils_success = fix_utils_urls()
    
    # Check all URL files
    all_issues = check_all_url_files()
    
    # Create test file
    test_success = create_media_test_file()
    
    print("\\n" + "=" * 60)
    if utils_success:
        print("🎉 UTILS MEDIA SERVING FIX COMPLETED!")
        print("✅ Removed problematic media serving from utils/urls.py")
        
        if all_issues:
            print(f"\\n⚠️ WARNING: Found {len(all_issues)} files with potential issues:")
            for file_path, issues in all_issues:
                print(f"   📄 {file_path}: {len(issues)} issues")
        else:
            print("✅ No other media serving patterns found")
        
        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")
        
        if test_success:
            print("\\n🧪 Test the fix:")
            print("   1. After restart, try: https://branchbusinessadvance.co.ke/media/test/test.txt")
            print("   2. Then test: https://branchbusinessadvance.co.ke/media/kyc/id_documents/FRONT-ID.jpeg")
        
    else:
        print("❌ UTILS MEDIA SERVING FIX FAILED!")
        print("Please check the error messages above")
    
    sys.exit(0 if utils_success else 1)