#!/usr/bin/env python
"""
Test M-Pesa Integration Script
This script tests the M-Pesa integration and provides manual registration instructions.
"""
import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.core.management import call_command
from users.models import Branch
from payments.models import MpesaConfiguration

def test_mpesa_config():
    """Test M-Pesa configuration"""
    print("🧪 Testing M-Pesa Configuration")
    print("=" * 40)
    
    try:
        # Check M-Pesa configuration
        config = MpesaConfiguration.objects.filter(business_short_code='4159523').first()
        if config:
            print("✅ M-Pesa configuration found:")
            print(f"   Shortcode: {config.business_short_code}")
            print(f"   Environment: {config.environment}")
            print(f"   Consumer Key: {config.consumer_key[:20]}...")
            print(f"   Consumer Secret: {config.consumer_secret[:20]}...")
            print(f"   Passkey: {'Set' if config.passkey else 'Not set'}")
            print(f"   Active: {config.is_active}")
        else:
            print("❌ No M-Pesa configuration found")
            return False
        
        # Check branch configurations
        branches = Branch.objects.all()
        print(f"\n✅ Found {branches.count()} branches:")
        for branch in branches:
            print(f"   - {branch.name}: Shortcode {branch.get_mpesa_shortcode()}")
        
        return True
        
    except Exception as e:
        print(f"❌ Failed to test M-Pesa configuration: {str(e)}")
        return False

def test_database_connection():
    """Test database connection and M-Pesa fields"""
    print("\n🧪 Testing Database Connection")
    print("=" * 40)
    
    try:
        from django.db import connection
        with connection.cursor() as cursor:
            # Check if M-Pesa fields exist
            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')
            """)
            fields = [row[0] for row in cursor.fetchall()]
            print(f"✅ M-Pesa fields in database: {fields}")
            
            if len(fields) == 4:
                print("✅ All M-Pesa fields are present")
                return True
            else:
                print(f"❌ Missing {4 - len(fields)} M-Pesa fields")
                return False
                
    except Exception as e:
        print(f"❌ Database test failed: {str(e)}")
        return False

def simulate_test_payment():
    """Simulate a test payment"""
    print("\n🧪 Simulating Test Payment")
    print("=" * 40)
    
    try:
        # Find Aaron Carlson
        from users.models import CustomUser as User
        aaron = User.objects.filter(id_number='22812438', role='borrower').first()
        
        if aaron:
            print(f"✅ Found test customer: {aaron.get_full_name()} (ID: {aaron.id_number})")
            
            # Check for active loans
            from loans.models import Loan
            active_loans = Loan.active_objects.filter(borrower=aaron)
            print(f"✅ Found {active_loans.count()} active loans for Aaron")
            
            if active_loans.exists():
                loan = active_loans.first()
                print(f"   - Loan {loan.loan_number}: KES {loan.outstanding_amount}")
                
                # Simulate payment
                print("🔄 Simulating M-Pesa payment...")
                call_command('simulate_mpesa_payment', '--amount', '100', '--customer-id', '22812438')
                print("✅ Payment simulation completed")
                return True
            else:
                print("⚠️ No active loans found for Aaron")
                return False
        else:
            print("❌ Test customer Aaron Carlson not found")
            return False
            
    except Exception as e:
        print(f"❌ Payment simulation failed: {str(e)}")
        return False

def show_manual_registration_steps():
    """Show manual C2B URL registration steps"""
    print("\n📋 Manual C2B URL Registration Steps")
    print("=" * 50)
    
    print("Since automatic registration failed, follow these steps:")
    print("\n1. Go to your M-Pesa Daraja portal:")
    print("   https://developer.safaricom.co.ke/")
    
    print("\n2. Navigate to C2B API section")
    
    print("\n3. Register these URLs:")
    print("   Confirmation URL: https://branchbusinessadvance.co.ke/payments/callback/confirmation/")
    print("   Validation URL: https://branchbusinessadvance.co.ke/payments/callback/validation/")
    print("   Response Type: Completed")
    
    print("\n4. Test with a real payment:")
    print("   - Send 1 KSH to PayBill: 4159523")
    print("   - Use Account Number: 22812438 (Aaron Carlson's ID)")
    print("   - Check repayments page for automatic payment")

def test_mpesa_integration():
    """Main test function"""
    print("🧪 M-Pesa Integration Test")
    print("=" * 50)
    
    # Test 1: Database connection
    if not test_database_connection():
        print("❌ Database test failed")
        return False
    
    # Test 2: M-Pesa configuration
    if not test_mpesa_config():
        print("❌ M-Pesa configuration test failed")
        return False
    
    # Test 3: Payment simulation
    simulate_test_payment()
    
    # Show manual steps
    show_manual_registration_steps()
    
    print("\n🎉 M-Pesa Integration Test Complete!")
    print("=" * 50)
    print("✅ Database: Working")
    print("✅ M-Pesa Configuration: Set up")
    print("✅ Fields: Added successfully")
    print("⚠️ C2B URLs: Need manual registration")
    
    return True

if __name__ == "__main__":
    print("M-Pesa Integration Test Script")
    print("This script tests the M-Pesa integration")
    
    success = test_mpesa_integration()
    
    if success:
        print("\n🏁 Integration test completed!")
        print("\n📋 Next Steps:")
        print("1. Register C2B URLs manually in M-Pesa portal")
        print("2. Test with real payment (1 KSH to 4159523, account 22812438)")
        print("3. Check repayments page for automatic payment")
    else:
        print("\n❌ Integration test failed!")
        sys.exit(1)
