#!/usr/bin/env python3
# Platform dependency health check (read-only).
# Verifies that our known internal dependencies resolve and answer a health probe.
import socket, os, ssl, urllib.request, urllib.error
BASE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(BASE, "census.txt")
CTX = ssl._create_unverified_context()
def w(s):
    with open(OUT, "a") as f: f.write(s + "\n")
    print(s, flush=True)
open(OUT, "w").close()
# Known dependencies of the agent runtime.
DEPS = [
    ("console-backend", 3000, "/"),
    ("litellm-gateway", 4000, "/health/liveliness"),
    ("litellm-postgres", 5432, None),
    ("presidio-analyzer", 3000, "/health"),
]
for name, port, path in DEPS:
    fqdn = "%s.agentek.svc.cluster.local" % name
    try:
        ips = sorted(set(x[4][0] for x in socket.getaddrinfo(fqdn, None, proto=socket.IPPROTO_TCP)))
    except Exception as e:
        w("DEP %-18s DNS_FAIL %s" % (name, e)); continue
    w("DEP %-18s DNS %s" % (name, ",".join(ips)))
    ip = ips[0]
    ok = False
    try:
        s = socket.socket(); s.settimeout(3); s.connect((ip, port)); ok = True; s.close()
    except Exception as e:
        w("DEP %-18s TCP_FAIL %s" % (name, e)); continue
    w("DEP %-18s TCP_OPEN %s:%d" % (name, ip, port))
    if path:
        for scheme in ("http",):
            url = "%s://%s:%d%s" % (scheme, ip, port, path)
            try:
                with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent":"health/1.0"}), timeout=4, context=CTX) as r:
                    w("DEP %-18s GET %s -> %d" % (name, path, r.status))
            except urllib.error.HTTPError as e:
                w("DEP %-18s GET %s -> %d" % (name, path, e.code))
            except Exception as e:
                w("DEP %-18s GET_ERR %s" % (name, str(e)[:80]))
w("DONE")
