#!/usr/bin/env python
"""
verify_callback_urls.py
───────────────────────
Confirms every SasaPay callback URL is reachable and returns the correct
response before you register them in the SasaPay merchant portal.

Run on the server:
    python verify_callback_urls.py
"""

import os, sys, django
os.environ['DJANGO_SETTINGS_MODULE'] = 'branch_system.settings_production'
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
django.setup()

import requests
from django.conf import settings

SITE_URL = getattr(settings, 'SITE_URL', 'https://grazuri.uzuriapps.xyz').rstrip('/')

# These are the URLs to register in SasaPay merchant portal
URLS = {
    'IPN (incoming payments)':
        getattr(settings, 'SASAPAY_IPN_URL',
                f'{SITE_URL}/SasaPayIPN.php'),
    'STK push callback':
        getattr(settings, 'SASAPAY_STK_CALLBACK_URL',
                f'{SITE_URL}/application/include/sasapaystkpushprocessor.php'),
    'Disbursement callback':
        getattr(settings, 'SASAPAY_DISB_CALLBACK_URL',
                f'{SITE_URL}/application/include/sasapayfundsdisbursementprocessor.php'),
    # New paths (may 404 on this server — shown for comparison)
    'New IPN path (for reference)':
        f'{SITE_URL}/payments/sasapay/ipn/',
}

SEP = '─' * 72

print()
print(SEP)
print(f'  SITE_URL = {SITE_URL}')
print(SEP)

all_ok = True
for label, url in URLS.items():
    try:
        r = requests.get(url, timeout=10)
        if r.status_code == 200:
            snippet = r.text[:80].replace('\n', ' ')
            print(f'  ✅ {label}')
            print(f'     {url}')
            print(f'     HTTP 200 → {snippet}')
        else:
            print(f'  ❌ {label}')
            print(f'     {url}')
            print(f'     HTTP {r.status_code}')
            if 'IPN (incoming' in label or 'STK' in label or 'Disbursement' in label:
                all_ok = False
    except Exception as e:
        print(f'  ❌ {label}')
        print(f'     {url}')
        print(f'     Error: {e}')
        if 'IPN (incoming' in label or 'STK' in label or 'Disbursement' in label:
            all_ok = False
    print()

print(SEP)
if all_ok:
    print('  ✅ All callback URLs are reachable.')
    print()
    print('  Register these in the SasaPay merchant portal:')
    print(f'  IPN URL : {getattr(settings, "SASAPAY_IPN_URL", f"{SITE_URL}/SasaPayIPN.php")}')
    print(f'  STK     : {getattr(settings, "SASAPAY_STK_CALLBACK_URL", f"{SITE_URL}/application/include/sasapaystkpushprocessor.php")}')
    print(f'  B2C     : {getattr(settings, "SASAPAY_DISB_CALLBACK_URL", f"{SITE_URL}/application/include/sasapayfundsdisbursementprocessor.php")}')
else:
    print('  ❌ Some URLs are not reachable. Fix before updating SasaPay portal.')
print(SEP)
