"""Wrapper to run outbound check and write results to file."""
import sys
import io

# Redirect stdout to file
outfile = open("E:\\genesis-system\\scripts\\outbound_result.txt", "w")
sys.stdout = outfile

import socket
import urllib.request
import ssl

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

tests = [
    # Tunneling services
    ("api.trycloudflare.com", 443, "Cloudflare Tunnel"),
    ("serveo.net", 22, "Serveo SSH tunnel"),
    ("serveo.net", 443, "Serveo HTTPS"),
    ("ngrok.com", 443, "ngrok HTTPS"),
    ("tunnel.us.ngrok.com", 443, "ngrok tunnel"),
    # Public DNS / internet reachability
    ("8.8.8.8", 53, "Google DNS"),
    ("1.1.1.1", 53, "Cloudflare DNS"),
    # Services known to work
    ("api.sunaivadigital.com", 443, "Sunaiva API"),
    ("api.telnyx.com", 443, "Telnyx API"),
    ("api.anthropic.com", 443, "Anthropic API"),
    # Railway / Render / Fly.io
    ("railway.app", 443, "Railway"),
    ("render.com", 443, "Render"),
    ("fly.io", 443, "Fly.io"),
    # GitHub (for git push deploy)
    ("github.com", 22, "GitHub SSH"),
    ("github.com", 443, "GitHub HTTPS"),
    # Direct VPS
    ("91.99.89.7", 22, "Sunaiva VPS SSH"),
    ("91.99.89.7", 443, "Sunaiva VPS HTTPS"),
]

print("=== Outbound Connectivity Matrix ===\n")
reachable = []
blocked = []
for host, port, label in tests:
    s = socket.socket()
    s.settimeout(4)
    result = s.connect_ex((host, port))
    s.close()
    status = "OPEN" if result == 0 else f"BLOCKED (err={result})"
    line = f"  {'OK  ' if result == 0 else 'FAIL'} {label:<30} {host}:{port}  {status}"
    print(line)
    if result == 0:
        reachable.append(label)
    else:
        blocked.append(label)

print(f"\nReachable ({len(reachable)}): {', '.join(reachable)}")
print(f"Blocked  ({len(blocked)}): {', '.join(blocked)}")

# HTTP test on working services
print("\n=== HTTP Reachability Test ===")
for url, label in [
    ("https://api.telnyx.com/v2", "Telnyx API"),
    ("https://railway.app", "Railway"),
    ("https://api.render.com/v1/services", "Render"),
]:
    try:
        req = urllib.request.Request(url, headers={"User-Agent": "Genesis/1.0"})
        with urllib.request.urlopen(req, timeout=6, context=ctx) as r:
            print(f"  OK   {label}: HTTP {r.status}")
    except Exception as e:
        print(f"  FAIL {label}: {str(e)[:60]}")

outfile.flush()
outfile.close()
