#!/usr/bin/env python
"""
Simple M-Pesa integration test
"""
import os
import sys
import django

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

from loans.models import MpesaTransaction
from payments.models import MpesaConfiguration
from payments.services import PaymentProcessor

def simple_test():
    print("🚀 Simple M-Pesa Integration Test...")
    
    # Check configuration
    config = MpesaConfiguration.get_active_config()
    if not config:
        print("❌ No M-Pesa configuration found")
        return False
    
    print(f"✅ Configuration: {config.business_short_code} ({config.environment})")
    print(f"   Validation URL: {config.validation_url}")
    print(f"   Confirmation URL: {config.confirmation_url}")
    
    # Test callback data
    callback_data = {
        "TransactionType": "Pay Bill",
        "TransID": "SIMPLE_TEST_123",
        "TransTime": "20241225120000",
        "TransAmount": "500.00",
        "BusinessShortCode": config.business_short_code,
        "BillRefNumber": "TEST_REF",
        "MSISDN": "254708374149",
        "FirstName": "Test",
        "LastName": "User"
    }
    
    print("\n📱 Testing validation callback...")
    try:
        response = PaymentProcessor.process_validation_callback(callback_data)
        print(f"✅ Validation response: {response}")
    except Exception as e:
        print(f"❌ Validation error: {e}")
        return False
    
    print("\n📱 Testing confirmation callback...")
    try:
        response = PaymentProcessor.process_confirmation_callback(callback_data)
        print(f"✅ Confirmation response: {response}")
        
        # Check transaction was created
        transaction = MpesaTransaction.objects.filter(trans_id="SIMPLE_TEST_123").first()
        if transaction:
            print(f"✅ Transaction created: {transaction}")
            print(f"   Status: {transaction.status}")
            print(f"   Amount: KES {transaction.amount}")
            print(f"   Phone: {transaction.get_phone_number()}")
            print(f"   Notes: {transaction.processing_notes}")
        else:
            print("❌ No transaction found")
            
    except Exception as e:
        print(f"❌ Confirmation error: {e}")
        return False
    
    print("\n🎉 Simple test completed!")
    return True

if __name__ == "__main__":
    success = simple_test()
    sys.exit(0 if success else 1)