#!/usr/bin/env python3
"""
Diagnostic script to identify the cause of 500 errors in production
"""

import os
import sys
import django
from pathlib import Path

def check_django_setup():
    """Check if Django is properly configured"""
    print("=== Django Setup Check ===")
    
    # Check if we're in the right directory
    if not os.path.exists('manage.py'):
        print("❌ manage.py not found in current directory")
        return False
    
    print("✅ manage.py found")
    
    # Check if settings module can be imported
    try:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')
        django.setup()
        print("✅ Django settings loaded successfully")
        return True
    except Exception as e:
        print(f"❌ Django setup failed: {e}")
        return False

def check_imports():
    """Check if all required modules can be imported"""
    print("\n=== Import Check ===")
    
    modules_to_check = [
        'utils.views',
        'utils.middleware',
        'utils.models',
        'users.models',
        'loans.models',
        'reports.models'
    ]
    
    for module in modules_to_check:
        try:
            __import__(module)
            print(f"✅ {module}")
        except Exception as e:
            print(f"❌ {module}: {e}")

def check_urls():
    """Check if URL patterns are valid"""
    print("\n=== URL Pattern Check ===")
    
    try:
        from django.urls import get_resolver
        from django.conf import settings
        
        resolver = get_resolver()
        print("✅ URL resolver created successfully")
        
        # Test a simple URL
        try:
            resolver.resolve('/admin/')
            print("✅ Admin URL resolves")
        except Exception as e:
            print(f"⚠️ Admin URL resolution: {e}")
            
    except Exception as e:
        print(f"❌ URL pattern check failed: {e}")

def check_middleware():
    """Check if middleware is properly configured"""
    print("\n=== Middleware Check ===")
    
    try:
        from django.conf import settings
        
        print(f"Middleware classes: {len(settings.MIDDLEWARE)}")
        for i, middleware in enumerate(settings.MIDDLEWARE):
            try:
                # Try to import the middleware
                module_path, class_name = middleware.rsplit('.', 1)
                module = __import__(module_path, fromlist=[class_name])
                middleware_class = getattr(module, class_name)
                print(f"✅ {middleware}")
            except Exception as e:
                print(f"❌ {middleware}: {e}")
                
    except Exception as e:
        print(f"❌ Middleware check failed: {e}")

def check_media_settings():
    """Check media file settings"""
    print("\n=== Media Settings Check ===")
    
    try:
        from django.conf import settings
        
        print(f"MEDIA_ROOT: {settings.MEDIA_ROOT}")
        print(f"MEDIA_URL: {settings.MEDIA_URL}")
        print(f"STATIC_ROOT: {settings.STATIC_ROOT}")
        print(f"STATIC_URL: {settings.STATIC_URL}")
        
        # Check if directories exist
        if os.path.exists(settings.MEDIA_ROOT):
            print("✅ MEDIA_ROOT exists")
        else:
            print("❌ MEDIA_ROOT does not exist")
            
        if os.path.exists(settings.STATIC_ROOT):
            print("✅ STATIC_ROOT exists")
        else:
            print("❌ STATIC_ROOT does not exist")
            
    except Exception as e:
        print(f"❌ Media settings check failed: {e}")

def check_database():
    """Check database connection"""
    print("\n=== Database Check ===")
    
    try:
        from django.db import connection
        from django.core.management import execute_from_command_line
        
        # Try to run a simple database query
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
            result = cursor.fetchone()
            if result:
                print("✅ Database connection successful")
            else:
                print("❌ Database query failed")
                
    except Exception as e:
        print(f"❌ Database check failed: {e}")

def check_views():
    """Check if views can be imported and instantiated"""
    print("\n=== Views Check ===")
    
    try:
        from utils import views
        
        # Check if views module has required attributes
        view_attributes = ['serve_media_file', 'test_media_access', 'simple_media_test']
        
        for attr in view_attributes:
            if hasattr(views, attr):
                print(f"✅ {attr} found")
            else:
                print(f"❌ {attr} not found")
                
    except Exception as e:
        print(f"❌ Views check failed: {e}")

def check_syntax():
    """Check for syntax errors in key files"""
    print("\n=== Syntax Check ===")
    
    files_to_check = [
        'utils/views.py',
        'utils/middleware.py',
        'utils/urls.py',
        'branch_system/urls.py',
        'branch_system/settings_production.py'
    ]
    
    for file_path in files_to_check:
        if os.path.exists(file_path):
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                compile(content, file_path, 'exec')
                print(f"✅ {file_path}")
            except SyntaxError as e:
                print(f"❌ {file_path}: {e}")
        else:
            print(f"⚠️ {file_path}: File not found")

def main():
    """Run all diagnostic checks"""
    print("🔍 Production Error Diagnostic Tool")
    print("=" * 50)
    
    # Run all checks
    django_ok = check_django_setup()
    
    if django_ok:
        check_imports()
        check_urls()
        check_middleware()
        check_media_settings()
        check_database()
        check_views()
        check_syntax()
    else:
        print("\n❌ Cannot proceed with other checks due to Django setup failure")
    
    print("\n" + "=" * 50)
    print("Diagnostic complete. Check the output above for any ❌ errors.")

if __name__ == "__main__":
    main() 