#!/usr/bin/env python3
"""
Production-specific fix for missing registration fee fields
Run this directly on the cPanel server
"""

import os
import sys
import django
from django.db import connection

# Setup Django for production
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')
django.setup()

def fix_production_fields():
    """Fix all registration fee fields in production"""
    print("🔧 PRODUCTION FIX: Adding missing registration fee fields...")
    
    # All registration fee fields that should exist
    required_fields = [
        ('registration_fee_amount', 'DECIMAL(10,2) NULL'),
        ('registration_fee_paid', 'BOOLEAN DEFAULT FALSE'),
        ('registration_fee_payment_date', 'DATETIME(6) NULL'),
        ('registration_fee_payment_method', 'VARCHAR(20) NULL'),
        ('registration_fee_receipt_number', 'VARCHAR(50) NULL'),
        ('registration_fee_notes', 'LONGTEXT NULL'),
    ]
    
    try:
        with connection.cursor() as cursor:
            print("📊 Checking current database schema...")
            
            # First, check what exists
            cursor.execute("""
                SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'users' 
                AND COLUMN_NAME LIKE 'registration_fee%'
                ORDER BY COLUMN_NAME
            """)
            
            existing_fields = cursor.fetchall()
            print(f"Found {len(existing_fields)} existing registration fee fields:")
            for field_name, data_type, is_nullable in existing_fields:
                print(f"  ✅ {field_name} ({data_type}, {is_nullable})")
            
            print("\n🔧 Adding missing fields...")
            
            for field_name, field_definition in required_fields:
                # Check if field exists
                cursor.execute("""
                    SELECT COUNT(*) 
                    FROM INFORMATION_SCHEMA.COLUMNS 
                    WHERE TABLE_SCHEMA = DATABASE() 
                    AND TABLE_NAME = 'users' 
                    AND COLUMN_NAME = %s
                """, [field_name])
                
                exists = cursor.fetchone()[0]
                
                if not exists:
                    print(f"  ➕ Adding {field_name}...")
                    try:
                        cursor.execute(f"""
                            ALTER TABLE users 
                            ADD COLUMN {field_name} {field_definition}
                        """)
                        print(f"  ✅ SUCCESS: Added {field_name}")
                    except Exception as e:
                        print(f"  ❌ ERROR adding {field_name}: {e}")
                else:
                    print(f"  ✅ {field_name} already exists")
            
            print("\n🧪 Testing field access...")
            
            # Test Django model access
            from django.contrib.auth import get_user_model
            User = get_user_model()
            
            # Clear any cached model info
            User._meta._expire_cache()
            
            # Try to access each field
            for field_name, _ in required_fields:
                try:
                    field = User._meta.get_field(field_name)
                    print(f"  ✅ Django field {field_name}: {field}")
                except Exception as e:
                    print(f"  ❌ Django field {field_name}: {e}")
            
            print("\n🔄 Refreshing Django model cache...")
            
            # Force Django to reload the model
            from django.apps import apps
            apps.clear_cache()
            
            # Reload the user model
            User = get_user_model()
            
            print("✅ Model cache refreshed")
            
        return True
        
    except Exception as e:
        print(f"❌ CRITICAL ERROR: {e}")
        return False

def test_user_query():
    """Test querying users with registration fee fields"""
    print("\n👤 Testing user queries...")
    
    try:
        from django.contrib.auth import get_user_model
        User = get_user_model()
        
        # Try to query with registration fee fields
        users = User.objects.all()[:1]
        
        for user in users:
            print(f"Testing user: {user.email}")
            try:
                # Access each registration fee field
                print(f"  registration_fee_amount: {user.registration_fee_amount}")
                print(f"  registration_fee_paid: {user.registration_fee_paid}")
                print(f"  registration_fee_payment_date: {user.registration_fee_payment_date}")
                print(f"  registration_fee_payment_method: {user.registration_fee_payment_method}")
                print(f"  registration_fee_receipt_number: {user.registration_fee_receipt_number}")
                print(f"  registration_fee_notes: {user.registration_fee_notes}")
                print("✅ All fields accessible")
            except Exception as e:
                print(f"❌ Field access error: {e}")
                return False
        
        return True
        
    except Exception as e:
        print(f"❌ Query error: {e}")
        return False

if __name__ == "__main__":
    print("🚀 PRODUCTION FIELD FIX STARTING...")
    print("=" * 60)
    
    success = fix_production_fields()
    
    if success:
        success = test_user_query()
    
    if success:
        print("\n" + "=" * 60)
        print("🎉 PRODUCTION FIX COMPLETED SUCCESSFULLY!")
        print("✅ All registration fee fields are now available")
        print("✅ Django model cache has been refreshed")
        print("✅ User queries are working properly")
        print("\n🔄 Please restart your web application to ensure changes take effect")
    else:
        print("\n" + "=" * 60)
        print("❌ PRODUCTION FIX FAILED!")
        print("Please check the error messages above and contact support")
    
    sys.exit(0 if success else 1)