#!/usr/bin/env python
"""
Production Register M-Pesa Callback URLs
Run this script on your cPanel production server to register callback URLs with M-Pesa
"""
import os
import sys
import django
import requests
import base64
import json

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

from payments.models import MpesaConfiguration

def register_callback_urls_with_mpesa():
    """Register callback URLs with M-Pesa Daraja API"""
    print("Registering M-Pesa Callback URLs")
    print("=" * 50)
    
    # Your M-Pesa credentials (from your production config)
    consumer_key = "9mD1A3H1qw5grqdqkZ4X1G9zbNxioydHXL5An4nkUGRlNRKr"
    consumer_secret = "C2dqBSaGFUIporfYYuyhQgnfPEqLvCS3GvfAJ91ENkXI2bhqptlVXAqMelsEpLQR"
    business_short_code = "4159523"
    
    # Your callback URLs
    validation_url = "https://branchbusinessadvance.co.ke/payments/callback/validation/"
    confirmation_url = "https://branchbusinessadvance.co.ke/payments/callback/confirmation/"
    
    print(f"Business Short Code: {business_short_code}")
    print(f"Validation URL: {validation_url}")
    print(f"Confirmation URL: {confirmation_url}")
    print()
    
    # Step 1: Get access token
    print("1. Getting M-Pesa access token...")
    try:
        # Encode credentials
        credentials = f"{consumer_key}:{consumer_secret}"
        encoded_credentials = base64.b64encode(credentials.encode()).decode()
        
        # Request access token
        token_url = "https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
        headers = {
            'Authorization': f'Basic {encoded_credentials}',
            'Content-Type': 'application/json'
        }
        
        response = requests.get(token_url, headers=headers)
        response.raise_for_status()
        
        token_data = response.json()
        access_token = token_data.get('access_token')
        
        if not access_token:
            print("❌ Failed to get access token")
            print(f"Response: {token_data}")
            return False
        
        print("✅ Access token obtained successfully")
        
    except Exception as e:
        print(f"❌ Error getting access token: {e}")
        return False
    
    # Step 2: Register callback URLs
    print("\n2. Registering callback URLs with M-Pesa...")
    try:
        register_url = "https://api.safaricom.co.ke/mpesa/c2b/v1/registerurl"
        
        headers = {
            'Authorization': f'Bearer {access_token}',
            'Content-Type': 'application/json'
        }
        
        payload = {
            "ShortCode": business_short_code,
            "ResponseType": "Completed",  # Complete transaction if validation URL is unreachable
            "ConfirmationURL": confirmation_url,
            "ValidationURL": validation_url
        }
        
        print(f"Registering URLs with payload: {json.dumps(payload, indent=2)}")
        
        response = requests.post(register_url, headers=headers, json=payload)
        response.raise_for_status()
        
        result = response.json()
        print("✅ Callback URLs registered successfully!")
        print(f"Response: {json.dumps(result, indent=2)}")
        
        # Check if registration was successful
        if result.get('ResponseCode') == '0':
            print("✅ URLs registered successfully with M-Pesa")
            print(f"Conversation ID: {result.get('OriginatorCoversationID')}")
            return True
        else:
            print(f"❌ Registration failed: {result.get('ResponseDescription')}")
            return False
            
    except Exception as e:
        print(f"❌ Error registering URLs: {e}")
        if hasattr(e, 'response') and e.response:
            print(f"Response: {e.response.text}")
        return False

def test_registered_urls():
    """Test if the registered URLs are working"""
    print("\n3. Testing registered callback URLs...")
    
    # Sample callback data (like what M-Pesa would send)
    sample_data = {
        "TransactionType": "Pay Bill",
        "TransID": "TEST123456789",
        "TransTime": "20251008062200",
        "TransAmount": "1.00",
        "BusinessShortCode": "4159523",
        "BillRefNumber": "40178864",
        "InvoiceNumber": "",
        "OrgAccountBalance": "1000.00",
        "ThirdPartyTransID": "",
        "MSISDN": "254700000100",
        "FirstName": "Phin",
        "MiddleName": "",
        "LastName": "Client"
    }
    
    urls = [
        "https://branchbusinessadvance.co.ke/payments/callback/validation/",
        "https://branchbusinessadvance.co.ke/payments/callback/confirmation/"
    ]
    
    for url in urls:
        print(f"Testing {url}")
        try:
            response = requests.post(
                url,
                json=sample_data,
                headers={'Content-Type': 'application/json'},
                timeout=10
            )
            print(f"   Status: {response.status_code}")
            print(f"   Response: {response.text[:100]}...")
            if response.status_code == 200:
                print("   ✅ URL is working")
            else:
                print(f"   ⚠️  URL returned status {response.status_code}")
        except Exception as e:
            print(f"   ❌ Error testing URL: {e}")
        print()

if __name__ == "__main__":
    success = register_callback_urls_with_mpesa()
    if success:
        test_registered_urls()
        
        print("\n" + "="*60)
        print("NEXT STEPS:")
        print("1. ✅ Callback URLs have been registered with M-Pesa")
        print("2. 🔄 Test with a real M-Pesa payment")
        print("3. 📱 Send 1 KES to paybill 4159523 with account 40178864")
        print("4. 📊 Check /payments/transactions/ for the callback")
        print("5. 🎯 The payment should now appear in your system!")
    else:
        print("\n❌ Failed to register callback URLs")
        print("Please check your M-Pesa credentials and try again")
