#!/usr/bin/env python
"""
Check M-Pesa Credentials Script
This script checks if the M-Pesa credentials are working correctly.
"""
import os
import sys
import django
import requests

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

def test_mpesa_access_token():
    """Test M-Pesa access token generation"""
    print("🔍 Testing M-Pesa Access Token")
    print("=" * 40)
    
    # Your production credentials
    consumer_key = "9mD1A3H1qw5grqdqkZ4X1G9zbNxioydHXL5An4nkUGRlNRKr"
    consumer_secret = "C2dqBSaGFUIporfYYuyhQgnfPEqLvCS3GvfAJ91ENkXI2bhqptlVXAqMelsEpLQR"
    
    print(f"Consumer Key: {consumer_key[:20]}...")
    print(f"Consumer Secret: {consumer_secret[:20]}...")
    
    # M-Pesa OAuth URL
    oauth_url = "https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
    
    try:
        print("🔄 Requesting access token...")
        response = requests.get(
            oauth_url,
            auth=(consumer_key, consumer_secret),
            headers={'Content-Type': 'application/json'},
            timeout=30
        )
        
        print(f"Status Code: {response.status_code}")
        print(f"Response: {response.text}")
        
        if response.status_code == 200:
            data = response.json()
            if 'access_token' in data:
                print("✅ Access token generated successfully!")
                print(f"Token: {data['access_token'][:20]}...")
                return True
            else:
                print("❌ No access token in response")
                return False
        else:
            print(f"❌ Failed to get access token: {response.status_code}")
            print(f"Error: {response.text}")
            return False
            
    except Exception as e:
        print(f"❌ Error requesting access token: {str(e)}")
        return False

def check_network_connectivity():
    """Check network connectivity to M-Pesa API"""
    print("\n🔍 Testing Network Connectivity")
    print("=" * 40)
    
    try:
        # Test basic connectivity
        response = requests.get("https://api.safaricom.co.ke", timeout=10)
        print(f"✅ Can reach M-Pesa API: {response.status_code}")
        return True
    except Exception as e:
        print(f"❌ Cannot reach M-Pesa API: {str(e)}")
        return False

def check_credentials_format():
    """Check if credentials are in correct format"""
    print("\n🔍 Checking Credentials Format")
    print("=" * 40)
    
    consumer_key = "9mD1A3H1qw5grqdqkZ4X1G9zbNxioydHXL5An4nkUGRlNRKr"
    consumer_secret = "C2dqBSaGFUIporfYYuyhQgnfPEqLvCS3GvfAJ91ENkXI2bhqptlVXAqMelsEpLQR"
    
    print(f"Consumer Key Length: {len(consumer_key)}")
    print(f"Consumer Secret Length: {len(consumer_secret)}")
    
    if len(consumer_key) > 0 and len(consumer_secret) > 0:
        print("✅ Credentials have content")
    else:
        print("❌ Credentials are empty")
        return False
    
    if consumer_key.isalnum() and consumer_secret.isalnum():
        print("✅ Credentials contain only alphanumeric characters")
    else:
        print("⚠️ Credentials contain special characters")
    
    return True

if __name__ == "__main__":
    print("M-Pesa Credentials Check Script")
    print("This script checks if M-Pesa credentials are working")
    
    # Check credentials format
    if not check_credentials_format():
        print("❌ Credentials format check failed")
        sys.exit(1)
    
    # Check network connectivity
    if not check_network_connectivity():
        print("❌ Network connectivity check failed")
        sys.exit(1)
    
    # Test access token
    if test_mpesa_access_token():
        print("\n✅ M-Pesa credentials are working!")
        print("The 400 error might be temporary or due to rate limiting.")
    else:
        print("\n❌ M-Pesa credentials are not working!")
        print("Check if:")
        print("1. Credentials are correct")
        print("2. Account is active")
        print("3. Network allows outbound HTTPS requests")
        print("4. No firewall blocking M-Pesa API")
