#!/usr/bin/env python
"""
Add M-Pesa Fields Manually Script
This script adds the M-Pesa fields to the Branch model manually via SQL.
Use this when migrations can't add the fields automatically.
"""
import os
import sys
import django

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

from django.db import connection

def add_mpesa_fields():
    """Add M-Pesa fields to the Branch model manually"""
    print("🔧 Adding M-Pesa Fields Manually")
    print("=" * 40)
    
    try:
        with connection.cursor() as cursor:
            # Check if fields already exist
            print("🔄 Checking existing fields...")
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'users_branch'
                AND COLUMN_NAME IN ('mpesa_shortcode', 'mpesa_consumer_key', 'mpesa_consumer_secret', 'mpesa_passkey')
            """)
            existing_fields = [row[0] for row in cursor.fetchall()]
            print(f"Existing M-Pesa fields: {existing_fields}")
            
            # Add missing fields
            fields_to_add = [
                ('mpesa_shortcode', 'VARCHAR(10) NULL'),
                ('mpesa_consumer_key', 'VARCHAR(100) NULL'),
                ('mpesa_consumer_secret', 'VARCHAR(100) NULL'),
                ('mpesa_passkey', 'VARCHAR(100) NULL'),
            ]
            
            for field_name, field_type in fields_to_add:
                if field_name not in existing_fields:
                    print(f"🔄 Adding field: {field_name}")
                    cursor.execute(f"ALTER TABLE users_branch ADD COLUMN {field_name} {field_type}")
                    print(f"✅ Added field: {field_name}")
                else:
                    print(f"✅ Field already exists: {field_name}")
            
            # Verify all fields were added
            print("🔄 Verifying all fields...")
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'users_branch'
                AND COLUMN_NAME IN ('mpesa_shortcode', 'mpesa_consumer_key', 'mpesa_consumer_secret', 'mpesa_passkey')
            """)
            final_fields = [row[0] for row in cursor.fetchall()]
            print(f"Final M-Pesa fields: {final_fields}")
            
            if len(final_fields) == 4:
                print("✅ All M-Pesa fields added successfully!")
                return True
            else:
                print(f"❌ Only {len(final_fields)}/4 fields were added")
                return False
                
    except Exception as e:
        print(f"❌ Failed to add M-Pesa fields: {str(e)}")
        return False

def test_mpesa_setup():
    """Test M-Pesa setup after adding fields"""
    print("\n🔄 Testing M-Pesa setup...")
    try:
        from django.core.management import call_command
        call_command('setup_production_mpesa', '--update-branches')
        print("✅ M-Pesa setup test successful!")
        return True
    except Exception as e:
        print(f"❌ M-Pesa setup test failed: {str(e)}")
        return False

if __name__ == "__main__":
    print("Add M-Pesa Fields Manually Script")
    print("This will add M-Pesa fields to the Branch model via SQL")
    
    # Add fields
    success = add_mpesa_fields()
    
    if success:
        print("\n🎉 M-Pesa fields added successfully!")
        
        # Test setup
        if test_mpesa_setup():
            print("\n✅ M-Pesa setup is now working!")
            print("\n📋 Next Steps:")
            print("1. Run the deployment script again")
            print("2. Test M-Pesa integration")
        else:
            print("\n⚠️ Fields added but M-Pesa setup still has issues")
    else:
        print("\n❌ Failed to add M-Pesa fields!")
        sys.exit(1)
