#!/usr/bin/env python
"""
Update Callback URLs Script
This script updates the M-Pesa configuration with the new callback URLs
that don't contain the word 'mpesa' to avoid M-Pesa restrictions.
"""
import os
import sys
import django

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

from payments.models import MpesaConfiguration

def update_callback_urls():
    """Update M-Pesa configuration with new callback URLs"""
    print("🔄 Updating M-Pesa Callback URLs")
    print("=" * 40)
    
    try:
        # Get the M-Pesa configuration
        config = MpesaConfiguration.objects.filter(business_short_code='4159523').first()
        
        if config:
            print("✅ Found M-Pesa configuration")
            print(f"   Current validation URL: {config.validation_url}")
            print(f"   Current confirmation URL: {config.confirmation_url}")
            
            # Update with new URLs
            new_validation_url = "https://branchbusinessadvance.co.ke/payments/callback/validation/"
            new_confirmation_url = "https://branchbusinessadvance.co.ke/payments/callback/confirmation/"
            
            config.validation_url = new_validation_url
            config.confirmation_url = new_confirmation_url
            config.save()
            
            print("✅ Updated M-Pesa configuration:")
            print(f"   New validation URL: {config.validation_url}")
            print(f"   New confirmation URL: {config.confirmation_url}")
            
            return True
        else:
            print("❌ No M-Pesa configuration found")
            return False
            
    except Exception as e:
        print(f"❌ Failed to update callback URLs: {str(e)}")
        return False

def test_new_urls():
    """Test that the new URLs are accessible"""
    print("\n🔄 Testing New Callback URLs")
    print("=" * 40)
    
    import requests
    
    urls_to_test = [
        "https://branchbusinessadvance.co.ke/payments/callback/validation/",
        "https://branchbusinessadvance.co.ke/payments/callback/confirmation/"
    ]
    
    for url in urls_to_test:
        try:
            print(f"🔄 Testing: {url}")
            response = requests.get(url, timeout=10)
            print(f"   Status: {response.status_code}")
            if response.status_code in [200, 405]:  # 405 is OK for POST-only endpoints
                print("   ✅ URL is accessible")
            else:
                print(f"   ⚠️ Unexpected status: {response.status_code}")
        except Exception as e:
            print(f"   ❌ Error: {str(e)}")

if __name__ == "__main__":
    print("Update Callback URLs Script")
    print("This script updates M-Pesa configuration with new callback URLs")
    
    # Update URLs
    success = update_callback_urls()
    
    if success:
        print("\n🎉 Callback URLs updated successfully!")
        
        # Test URLs
        test_new_urls()
        
        print("\n📋 Next Steps:")
        print("1. Register the new URLs in M-Pesa portal:")
        print("   - Confirmation URL: https://branchbusinessadvance.co.ke/payments/callback/confirmation/")
        print("   - Validation URL: https://branchbusinessadvance.co.ke/payments/callback/validation/")
        print("2. Test with a real payment")
    else:
        print("\n❌ Failed to update callback URLs!")
        sys.exit(1)
