#!/usr/bin/env python3
"""
Clear Django cache and force model refresh
"""

import os
import sys
import django
from django.db import connection
from django.core.management import call_command

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

def clear_django_cache():
    """Clear Django's internal caches"""
    print("🧹 Clearing Django caches...")
    
    try:
        # Clear Django's app registry cache
        from django.apps import apps
        apps.clear_cache()
        print("✅ Cleared Django apps cache")
        
        # Clear migration loader cache
        from django.db.migrations.loader import MigrationLoader
        loader = MigrationLoader(connection)
        loader.build_graph()
        print("✅ Rebuilt migration graph")
        
        # Force model refresh
        from django.contrib.auth import get_user_model
        User = get_user_model()
        User._meta._expire_cache()
        print("✅ Expired User model cache")
        
        return True
        
    except Exception as e:
        print(f"❌ ERROR: {e}")
        return False

def test_login_view():
    """Test the login view that's causing the error"""
    print("\n🔐 Testing login functionality...")
    
    try:
        from django.contrib.auth import get_user_model
        from django.contrib.auth import authenticate
        
        User = get_user_model()
        
        # Try to get the admin user
        admin_user = User.objects.get(email='admin@branchbusinessadvance.com')
        print(f"✅ Found admin user: {admin_user.email}")
        
        # Check all registration fee fields
        reg_fields = [
            'registration_fee_amount',
            'registration_fee_paid', 
            'registration_fee_payment_date',
            'registration_fee_payment_method',
            'registration_fee_receipt_number',
            'registration_fee_notes'
        ]
        
        print("📋 Checking registration fee fields on admin user:")
        for field in reg_fields:
            try:
                value = getattr(admin_user, field)
                print(f"  ✅ {field}: {value}")
            except AttributeError as e:
                print(f"  ❌ {field}: {e}")
        
        return True
        
    except Exception as e:
        print(f"❌ ERROR: {e}")
        return False

def run_migrations():
    """Run migrations to ensure everything is up to date"""
    print("\n🔄 Running migrations...")
    
    try:
        call_command('migrate', verbosity=1)
        print("✅ Migrations completed")
        return True
        
    except Exception as e:
        print(f"❌ ERROR: {e}")
        return False

if __name__ == "__main__":
    print("🚀 Clearing Django cache and testing...")
    clear_django_cache()
    test_login_view()
    run_migrations()
    print("🎉 Cache clearing completed!")