"""
Daraja Connection Diagnostic
==============================
Run on the production server to check if it can reach Safaricom's Daraja API.

    python check_daraja_connection.py

Tests:
  1. DNS resolution of api.safaricom.co.ke
  2. TCP connection to port 443
  3. HTTPS request via Python requests
  4. curl fallback (if requests fails)
  5. Control test against api.sasapay.app (known working)
"""

import socket
import subprocess
import sys

try:
    import requests
except ImportError:
    print("Installing requests...")
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--quiet', '--user', 'requests'])
    import requests

DARAJA_HOST = 'api.safaricom.co.ke'
SASAPAY_HOST = 'api.sasapay.app'

SEP = '=' * 60


def check_dns(host):
    """Check if the host resolves via DNS."""
    try:
        ips = socket.getaddrinfo(host, 443)
        unique_ips = list(set(ip[4][0] for ip in ips))
        print(f"  DNS resolves to: {', '.join(unique_ips)}")
        return True
    except socket.gaierror as e:
        print(f"  DNS FAILED: {e}")
        return False


def check_tcp(host):
    """Check if we can open a TCP connection to port 443."""
    try:
        sock = socket.create_connection((host, 443), timeout=10)
        sock.close()
        print("  TCP connection to port 443: OK")
        return True
    except (socket.timeout, OSError) as e:
        print(f"  TCP connection FAILED: {e}")
        return False


def check_https(host, path='/'):
    """Check if we can make an HTTPS request."""
    url = f'https://{host}{path}'
    try:
        r = requests.get(url, timeout=15)
        print(f"  HTTPS request returned status {r.status_code}")
        return True
    except requests.exceptions.ConnectTimeout:
        print(f"  HTTPS request TIMED OUT (15s)")
        return False
    except requests.exceptions.ConnectionError as e:
        print(f"  HTTPS request FAILED: {e}")
        return False


def check_curl(host, path='/'):
    """Try curl as a fallback."""
    url = f'https://{host}{path}'
    try:
        result = subprocess.run(
            ['curl', '-s', '-o', '/dev/null', '-w', '%{http_code}',
             '--connect-timeout', '15', url],
            capture_output=True, text=True, timeout=20
        )
        code = result.stdout.strip()
        if code and code != '000':
            print(f"  curl returned HTTP {code}")
            return True
        else:
            print(f"  curl FAILED (exit code {result.returncode}): {result.stderr[:100]}")
            return False
    except FileNotFoundError:
        print("  curl not found on this server")
        return False
    except Exception as e:
        print(f"  curl FAILED: {e}")
        return False


print(f"\n{SEP}")
print("  Daraja Connection Diagnostic")
print(f"{SEP}")

for label, host in [("DARAJA", DARAJA_HOST), ("SASAPAY (control)", SASAPAY_HOST)]:
    print(f"\n--- {label}: {host} ---")

    print("  [1] DNS:")
    dns_ok = check_dns(host)

    print("  [2] TCP:")
    if dns_ok:
        tcp_ok = check_tcp(host)
    else:
        print("  Skipped (DNS failed)")
        tcp_ok = False

    print("  [3] HTTPS (Python requests):")
    if tcp_ok:
        https_ok = check_https(host)
    else:
        print("  Skipped (TCP failed)")
        https_ok = False

    print("  [4] curl fallback:")
    if not https_ok:
        curl_ok = check_curl(host)
    else:
        print("  Skipped (HTTPS worked)")

print(f"\n{SEP}")
print("  SUMMARY")
print(f"{SEP}")

if not dns_ok:
    print("  DNS resolution failed — contact your hosting provider.")
    print("  The server cannot resolve api.safaricom.co.ke.")
elif not tcp_ok:
    print("  TCP connection blocked — your hosting firewall is blocking")
    print("  outbound connections to api.safaricom.co.ke:443.")
    print("  Contact your hosting provider to whitelist this host.")
elif not https_ok:
    print("  HTTPS request failed — possible SSL or proxy issue.")
    print("  Check if your server requires a proxy for outbound HTTPS.")
else:
    print("  Connection to Daraja API is working!")
    print("  The STK push timeout issue may be temporary — try again.")
