#!/usr/bin/env python
"""
Production Test M-Pesa Callback URLs with POST
Run this script on your cPanel production server to test callback URLs with POST requests
"""
import os
import sys
import django
import requests
import json

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from payments.models import MpesaConfiguration

def test_production_callback_urls_post():
    """Test if production callback URLs accept POST requests"""
    print("Testing Production M-Pesa Callback URLs with POST")
    print("=" * 60)
    
    # Get production configuration
    configs = MpesaConfiguration.objects.all()
    
    if not configs.exists():
        print("❌ No M-Pesa configurations found!")
        return
    
    for config in configs:
        print(f"Testing configuration for shortcode: {config.business_short_code}")
        print(f"Environment: {config.environment}")
        print()
        
        # Sample M-Pesa callback data
        sample_callback_data = {
            "TransactionType": "Pay Bill",
            "TransID": "TJ8016VP0B",
            "TransTime": "20251008062200",
            "TransAmount": "1.00",
            "BusinessShortCode": "4159523",
            "BillRefNumber": "40178864",
            "InvoiceNumber": "",
            "OrgAccountBalance": "1000.00",
            "ThirdPartyTransID": "",
            "MSISDN": "254700000100",
            "FirstName": "Phin",
            "MiddleName": "",
            "LastName": "Client"
        }
        
        # Test validation URL with POST
        print(f"Testing validation URL with POST: {config.validation_url}")
        try:
            response = requests.post(
                config.validation_url, 
                json=sample_callback_data,
                headers={'Content-Type': 'application/json'},
                timeout=10
            )
            print(f"   Status Code: {response.status_code}")
            print(f"   Response: {response.text[:200]}...")
            if response.status_code == 200:
                print("   ✅ Validation URL accepts POST requests")
            else:
                print(f"   ⚠️  Validation URL returned status {response.status_code}")
        except requests.exceptions.RequestException as e:
            print(f"   ❌ Validation URL not accessible: {e}")
        
        print()
        
        # Test confirmation URL with POST
        print(f"Testing confirmation URL with POST: {config.confirmation_url}")
        try:
            response = requests.post(
                config.confirmation_url, 
                json=sample_callback_data,
                headers={'Content-Type': 'application/json'},
                timeout=10
            )
            print(f"   Status Code: {response.status_code}")
            print(f"   Response: {response.text[:200]}...")
            if response.status_code == 200:
                print("   ✅ Confirmation URL accepts POST requests")
            else:
                print(f"   ⚠️  Confirmation URL returned status {response.status_code}")
        except requests.exceptions.RequestException as e:
            print(f"   ❌ Confirmation URL not accessible: {e}")
        
        print()
        print("-" * 60)
        print()
    
    print("ANALYSIS:")
    print("1. HTTP 405 = Method Not Allowed (URLs reject GET requests)")
    print("2. This is NORMAL for M-Pesa callback URLs")
    print("3. M-Pesa sends POST requests, not GET requests")
    print("4. If POST requests work, your URLs are configured correctly")
    print("5. The issue might be that M-Pesa hasn't registered these URLs yet")

if __name__ == "__main__":
    test_production_callback_urls_post()
