#!/usr/bin/env python
"""
Update Callback URLs Script
Updates the M-Pesa configuration with the correct callback URLs for this deployment
and re-registers them with Safaricom.
"""
import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.conf import settings
from payments.models import MpesaConfiguration

# Derive the correct base URL from settings (never hardcode the domain here)
SITE_URL = getattr(settings, 'SITE_URL', 'https://grazuri.uzuriapps.xyz').rstrip('/')
NEW_VALIDATION_URL   = f"{SITE_URL}/payments/callback/validation/"
NEW_CONFIRMATION_URL = f"{SITE_URL}/payments/callback/confirmation/"


def update_callback_urls():
    """Update M-Pesa configuration with correct callback URLs"""
    print("🔄 Updating M-Pesa Callback URLs")
    print("=" * 50)
    print(f"   Target domain : {SITE_URL}")

    try:
        config = MpesaConfiguration.objects.filter(business_short_code='4159523').first()

        if not config:
            print("❌ No M-Pesa configuration found for shortcode 4159523")
            return None

        print(f"✅ Found M-Pesa configuration")
        print(f"   Old validation URL  : {config.validation_url}")
        print(f"   Old confirmation URL: {config.confirmation_url}")

        config.validation_url   = NEW_VALIDATION_URL
        config.confirmation_url = NEW_CONFIRMATION_URL
        config.save(update_fields=['validation_url', 'confirmation_url'])

        print(f"\n✅ Updated M-Pesa configuration:")
        print(f"   New validation URL  : {config.validation_url}")
        print(f"   New confirmation URL: {config.confirmation_url}")
        return config

    except Exception as e:
        print(f"❌ Failed to update callback URLs: {str(e)}")
        return None


def register_urls_with_safaricom(config):
    """Re-register the updated URLs with Safaricom so callbacks reach this server."""
    print("\n🔄 Registering URLs with Safaricom")
    print("=" * 50)
    try:
        from payments.services import MpesaService
        service = MpesaService(config)
        result = service.register_urls(
            validation_url=config.validation_url,
            confirmation_url=config.confirmation_url,
        )
        print(f"✅ URLs registered with Safaricom: {result}")
        return True
    except Exception as e:
        print(f"❌ Registration failed: {str(e)}")
        print("   You may need to register the URLs manually in the M-Pesa portal.")
        return False


def test_new_urls():
    """Verify the new URLs are reachable from this server."""
    print("\n🔄 Testing Callback URL Reachability")
    print("=" * 50)
    import requests
    for url in [NEW_VALIDATION_URL, NEW_CONFIRMATION_URL]:
        try:
            response = requests.get(url, timeout=10)
            # 200 or 405 (POST-only) both mean the URL is live
            if response.status_code in [200, 405]:
                print(f"   ✅ {url}")
            else:
                print(f"   ⚠️  {url}  →  HTTP {response.status_code}")
        except Exception as e:
            print(f"   ❌ {url}  →  {e}")


if __name__ == "__main__":
    print("M-Pesa Callback URL Updater")
    print("=" * 50)

    config = update_callback_urls()

    if config:
        register_urls_with_safaricom(config)
        test_new_urls()

        print("\n📋 Summary")
        print("=" * 50)
        print(f"  Confirmation URL : {NEW_CONFIRMATION_URL}")
        print(f"  Validation URL   : {NEW_VALIDATION_URL}")
        print("\n  If Safaricom registration failed above, log into the M-Pesa portal")
        print("  (https://developer.safaricom.co.ke) and register these URLs manually.")
    else:
        print("\n❌ Update failed — no changes were made.")
        sys.exit(1)
