#!/usr/bin/env python3
"""
Check database schema vs Django model expectations
"""

import os
import sys
import django
from django.db import connection

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

def check_database_schema():
    """Check the actual database schema"""
    print("🔍 Checking database schema...")
    
    try:
        with connection.cursor() as cursor:
            # Get all columns in users table
            cursor.execute("""
                SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'users' 
                ORDER BY COLUMN_NAME
            """)
            
            columns = cursor.fetchall()
            
            print(f"📊 Found {len(columns)} columns in users table:")
            print("-" * 80)
            
            registration_fee_columns = []
            for column_name, data_type, is_nullable, default_value in columns:
                if 'registration_fee' in column_name:
                    registration_fee_columns.append(column_name)
                print(f"{column_name:<35} {data_type:<15} {is_nullable:<10} {default_value or 'NULL'}")
            
            print("-" * 80)
            print(f"🏦 Registration fee related columns ({len(registration_fee_columns)}):")
            for col in registration_fee_columns:
                print(f"  ✅ {col}")
            
            # Check if the specific column causing the error exists
            cursor.execute("""
                SELECT COUNT(*) 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'users' 
                AND COLUMN_NAME = 'registration_fee_receipt_number'
            """)
            
            exists = cursor.fetchone()[0]
            if exists:
                print("✅ registration_fee_receipt_number column EXISTS in database")
            else:
                print("❌ registration_fee_receipt_number column MISSING from database")
                
        return True
        
    except Exception as e:
        print(f"❌ ERROR: {e}")
        return False

def test_django_model():
    """Test Django model field access"""
    print("\n🧪 Testing Django model field access...")
    
    try:
        from django.contrib.auth import get_user_model
        User = get_user_model()
        
        # Get model fields
        field_names = [field.name for field in User._meta.get_fields()]
        registration_fields = [f for f in field_names if 'registration_fee' in f]
        
        print(f"📋 Django model has {len(registration_fields)} registration fee fields:")
        for field in registration_fields:
            print(f"  ✅ {field}")
        
        # Try to access the problematic field
        try:
            field = User._meta.get_field('registration_fee_receipt_number')
            print(f"✅ Field 'registration_fee_receipt_number' found in Django model: {field}")
        except Exception as e:
            print(f"❌ Field 'registration_fee_receipt_number' not found in Django model: {e}")
            
        return True
        
    except Exception as e:
        print(f"❌ ERROR: {e}")
        return False

def test_user_creation():
    """Test creating a user to see what fails"""
    print("\n👤 Testing user creation...")
    
    try:
        from django.contrib.auth import get_user_model
        User = get_user_model()
        
        # Try to create a test user
        test_user = User(
            username='test_user_schema',
            email='test@example.com',
            first_name='Test',
            last_name='User'
        )
        
        # Try to access the problematic field
        test_user.registration_fee_receipt_number = 'TEST123'
        print("✅ Successfully set registration_fee_receipt_number on user object")
        
        # Don't save, just test field access
        print("✅ User object creation and field access successful")
        
        return True
        
    except Exception as e:
        print(f"❌ ERROR: {e}")
        return False

if __name__ == "__main__":
    print("🚀 Running comprehensive database schema check...")
    check_database_schema()
    test_django_model()
    test_user_creation()
    print("🎉 Schema check completed!")