#!/usr/bin/env python
"""
Production Check M-Pesa Credentials
Run this script on your cPanel production server to check M-Pesa credentials and permissions
"""
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 check_mpesa_credentials():
    """Check M-Pesa credentials and permissions"""
    print("Checking M-Pesa Credentials and Permissions")
    print("=" * 50)
    
    # Your M-Pesa credentials
    consumer_key = "9mD1A3H1qw5grqdqkZ4X1G9zbNxioydHXL5An4nkUGRlNRKr"
    consumer_secret = "C2dqBSaGFUIporfYYuyhQgnfPEqLvCS3GvfAJ91ENkXI2bhqptlVXAqMelsEpLQR"
    business_short_code = "4159523"
    
    print(f"Consumer Key: {consumer_key[:20]}...")
    print(f"Business Short Code: {business_short_code}")
    print()
    
    # Step 1: Test access token generation
    print("1. Testing access token generation...")
    try:
        credentials = f"{consumer_key}:{consumer_secret}"
        encoded_credentials = base64.b64encode(credentials.encode()).decode()
        
        # Try production first
        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, timeout=10)
        print(f"Production token response: {response.status_code}")
        
        if response.status_code == 200:
            token_data = response.json()
            access_token = token_data.get('access_token')
            if access_token:
                print("✅ Production access token obtained successfully")
                print(f"Token: {access_token[:20]}...")
                return access_token, "production"
            else:
                print("❌ No access token in response")
                print(f"Response: {token_data}")
        else:
            print(f"❌ Production token failed: {response.status_code}")
            print(f"Response: {response.text}")
            
    except Exception as e:
        print(f"❌ Error getting production token: {e}")
    
    # Step 2: Try sandbox if production fails
    print("\n2. Trying sandbox credentials...")
    try:
        sandbox_token_url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
        response = requests.get(sandbox_token_url, headers=headers, timeout=10)
        print(f"Sandbox token response: {response.status_code}")
        
        if response.status_code == 200:
            token_data = response.json()
            access_token = token_data.get('access_token')
            if access_token:
                print("✅ Sandbox access token obtained successfully")
                print(f"Token: {access_token[:20]}...")
                return access_token, "sandbox"
            else:
                print("❌ No access token in sandbox response")
                print(f"Response: {token_data}")
        else:
            print(f"❌ Sandbox token failed: {response.status_code}")
            print(f"Response: {response.text}")
            
    except Exception as e:
        print(f"❌ Error getting sandbox token: {e}")
    
    return None, None

def test_register_url_permissions(access_token, environment):
    """Test if we can register URLs with the obtained token"""
    print(f"\n3. Testing URL registration permissions ({environment})...")
    
    business_short_code = "4159523"
    validation_url = "https://branchbusinessadvance.co.ke/payments/callback/validation/"
    confirmation_url = "https://branchbusinessadvance.co.ke/payments/callback/confirmation/"
    
    if environment == "production":
        register_url = "https://api.safaricom.co.ke/mpesa/c2b/v1/registerurl"
    else:
        register_url = "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl"
        # Use sandbox shortcode for testing
        business_short_code = "174379"
    
    try:
        headers = {
            'Authorization': f'Bearer {access_token}',
            'Content-Type': 'application/json'
        }
        
        payload = {
            "ShortCode": business_short_code,
            "ResponseType": "Completed",
            "ConfirmationURL": confirmation_url,
            "ValidationURL": validation_url
        }
        
        print(f"Testing with shortcode: {business_short_code}")
        print(f"Register URL: {register_url}")
        
        response = requests.post(register_url, headers=headers, json=payload, timeout=10)
        print(f"Registration response: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            print("✅ URL registration successful!")
            print(f"Response: {json.dumps(result, indent=2)}")
            return True
        else:
            print(f"❌ URL registration failed: {response.status_code}")
            print(f"Response: {response.text}")
            return False
            
    except Exception as e:
        print(f"❌ Error testing registration: {e}")
        return False

def check_shortcode_permissions():
    """Check if the shortcode has the right permissions"""
    print("\n4. Checking shortcode permissions...")
    print("IMPORTANT NOTES:")
    print("1. Shortcode 4159523 must be registered for C2B transactions")
    print("2. The shortcode owner must enable C2B callbacks")
    print("3. You may need to contact Safaricom to enable C2B for your shortcode")
    print("4. Email: apisupport@safaricom.co.ke or M-pesabusiness@safaricom.co.ke")
    print()
    print("REQUIRED ACTIONS:")
    print("1. Contact Safaricom to enable C2B for shortcode 4159523")
    print("2. Request callback URL registration permissions")
    print("3. Provide these URLs to Safaricom:")
    print("   - Validation: https://branchbusinessadvance.co.ke/payments/callback/validation/")
    print("   - Confirmation: https://branchbusinessadvance.co.ke/payments/callback/confirmation/")

if __name__ == "__main__":
    access_token, environment = check_mpesa_credentials()
    
    if access_token:
        success = test_register_url_permissions(access_token, environment)
        if not success:
            check_shortcode_permissions()
    else:
        print("\n❌ Could not obtain access token")
        print("Please check your M-Pesa credentials")
        check_shortcode_permissions()
