"""
Register M-Pesa callback URLs for both branches
This script programmatically registers the validation and confirmation URLs with Safaricom
"""
import os
import django
import requests
import base64
import json
from datetime import datetime

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

from users.models import Branch
from django.conf import settings

print("=" * 80)
print("M-PESA CALLBACK URL REGISTRATION")
print("=" * 80)

# Get domain from command-line arguments or use default
import sys

if len(sys.argv) > 1:
    DOMAIN = sys.argv[1].strip()
    print(f"\nUsing domain from command line: {DOMAIN}")
else:
    # Try to auto-detect from settings
    try:
        from django.conf import settings
        if hasattr(settings, 'ALLOWED_HOSTS') and settings.ALLOWED_HOSTS:
            # Use first allowed host that's not localhost or wildcard
            for host in settings.ALLOWED_HOSTS:
                if host not in ['*', 'localhost', '127.0.0.1', '.localhost']:
                    DOMAIN = host
                    break
            else:
                DOMAIN = 'branchbusinessadvance.co.ke'
        else:
            DOMAIN = 'branchbusinessadvance.co.ke'
        print(f"\nAuto-detected domain: {DOMAIN}")
    except:
        DOMAIN = 'branchbusinessadvance.co.ke'
        print(f"\nUsing default domain: {DOMAIN}")

# Ensure HTTPS
if not DOMAIN.startswith('http'):
    DOMAIN = f"https://{DOMAIN}"

VALIDATION_URL = f"{DOMAIN}/payments/callback/validation/"
CONFIRMATION_URL = f"{DOMAIN}/payments/callback/confirmation/"

print(f"\nCallback URLs to register:")
print(f"  Validation: {VALIDATION_URL}")
print(f"  Confirmation: {CONFIRMATION_URL}")

# Get branches
branches = Branch.objects.filter(
    mpesa_shortcode__isnull=False
).exclude(mpesa_shortcode='')

if not branches.exists():
    print("\n⚠ No branches with M-Pesa shortcodes found!")
    print("Please run setup_branch_mpesa.py first.")
    exit(1)

def get_access_token(consumer_key, consumer_secret, environment='production'):
    """Get M-Pesa access token"""
    if environment == 'production':
        url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials'
    else:
        url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials'
    
    # Create basic auth header
    auth_string = f"{consumer_key}:{consumer_secret}"
    auth_bytes = auth_string.encode('ascii')
    auth_b64 = base64.b64encode(auth_bytes).decode('ascii')
    
    headers = {
        'Authorization': f'Basic {auth_b64}',
        'Content-Type': 'application/json'
    }
    
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        return response.json()['access_token']
    except Exception as e:
        print(f"Error getting access token: {str(e)}")
        return None

def register_urls(shortcode, consumer_key, consumer_secret, environment='production'):
    """Register C2B URLs with Safaricom"""
    print(f"\n{'=' * 80}")
    print(f"Registering URLs for Shortcode: {shortcode}")
    print(f"{'=' * 80}")
    
    # Get access token
    print("Getting access token...")
    access_token = get_access_token(consumer_key, consumer_secret, environment)
    
    if not access_token:
        print("✗ Failed to get access token!")
        return False
    
    print("✓ Access token obtained")
    
    # Register URLs - Using v2 endpoint as per Safaricom API Support
    if environment == 'production':
        url = 'https://api.safaricom.co.ke/mpesa/c2b/v2/registerurl'
    else:
        url = 'https://sandbox.safaricom.co.ke/mpesa/c2b/v2/registerurl'
    
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }
    
    payload = {
        'ShortCode': shortcode,
        'ResponseType': 'Completed',  # or 'Cancelled'
        'ConfirmationURL': CONFIRMATION_URL,
        'ValidationURL': VALIDATION_URL
    }
    
    print(f"\nSending registration request...")
    print(f"Payload: {json.dumps(payload, indent=2)}")
    
    try:
        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()
        result = response.json()
        
        print(f"\n✓ Registration successful!")
        print(f"Response: {json.dumps(result, indent=2)}")
        return True
        
    except requests.exceptions.HTTPError as e:
        print(f"\n✗ Registration failed!")
        print(f"Status Code: {e.response.status_code}")
        print(f"Response: {e.response.text}")
        return False
    except Exception as e:
        print(f"\n✗ Error: {str(e)}")
        return False

# Main execution
print("\n" + "=" * 80)
print("Starting URL Registration Process")
print("=" * 80)

# Get environment from command-line or use production as default
if len(sys.argv) > 2:
    environment = sys.argv[2].strip().lower()
    print(f"\nUsing environment from command line: {environment}")
else:
    environment = 'production'
    print(f"\nUsing default environment: {environment}")

results = []
for branch in branches:
    success = register_urls(
        shortcode=branch.mpesa_shortcode,
        consumer_key=branch.mpesa_consumer_key,
        consumer_secret=branch.mpesa_consumer_secret,
        environment=environment
    )
    results.append({
        'branch': branch.name,
        'shortcode': branch.mpesa_shortcode,
        'success': success
    })

# Summary
print("\n" + "=" * 80)
print("REGISTRATION SUMMARY")
print("=" * 80)

for result in results:
    status = "✓ SUCCESS" if result['success'] else "✗ FAILED"
    print(f"\n{result['branch']} (Shortcode: {result['shortcode']})")
    print(f"  {status}")

print("\n" + "=" * 80)
print("REGISTRATION COMPLETE")
print("=" * 80)

if all(r['success'] for r in results):
    print("\n✓ All callback URLs registered successfully!")
    print("\nNext steps:")
    print("1. Test payments to both paybills")
    print("2. Check admin panel for incoming callbacks")
    print("3. Monitor transaction processing")
else:
    print("\n⚠ Some registrations failed!")
    print("\nPlease:")
    print("1. Verify your credentials are correct")
    print("2. Check if paybills are active")
    print("3. Ensure you have API access enabled")
    print("4. Contact Safaricom support if needed")
    print("\nAlternatively, register URLs manually via Safaricom portal")
