import http.client, json, socket, ssl, statistics, time, urllib.request, datetime, subprocess
HOST = "clob.polymarket.com"
out = {"started_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")}
def md(path):
    tok = urllib.request.urlopen(urllib.request.Request("http://169.254.169.254/latest/api/token", method="PUT", headers={"X-aws-ec2-metadata-token-ttl-seconds": "60"}), timeout=2).read().decode()
    return urllib.request.urlopen(urllib.request.Request("http://169.254.169.254/latest/meta-data/" + path, headers={"X-aws-ec2-metadata-token": tok}), timeout=2).read().decode()
try:
    out["instance_type"] = md("instance-type"); out["az"] = md("placement/availability-zone"); out["az_id"] = md("placement/availability-zone-id")
except Exception as e:
    out["metadata_error"] = repr(e)
out["python"] = subprocess.run(["python3", "--version"], capture_output=True, text=True).stdout.strip()
out["kernel"] = subprocess.run(["uname", "-r"], capture_output=True, text=True).stdout.strip()

def stats(xs):
    xs = sorted(xs); n = len(xs)
    def pct(p):
        k = (n - 1) * p; f = int(k); c = min(f + 1, n - 1)
        return xs[f] + (xs[c] - xs[f]) * (k - f)
    return {"n": n, "min": round(xs[0], 2), "median": round(statistics.median(xs), 2), "mean": round(statistics.fmean(xs), 2),
            "p90": round(pct(0.90), 2), "p95": round(pct(0.95), 2), "p99": round(pct(0.99), 2), "max": round(xs[-1], 2)}

# Pick the most traded open market for the order book request.
token = None
try:
    req = urllib.request.Request("https://gamma-api.polymarket.com/markets?limit=1&active=true&closed=false&order=volume24hr&ascending=false", headers={"User-Agent": "latency-check"})
    m = json.loads(urllib.request.urlopen(req, timeout=10).read())[0]
    token = json.loads(m["clobTokenIds"])[0]
    out["market"] = {"question": m.get("question"), "slug": m.get("slug"), "token_id": token}
except Exception as e:
    out["market_error"] = repr(e)

# Cold connections: DNS, TCP, TLS and first byte, a new connection each time.
ctx = ssl.create_default_context()
dns, tcp, tls, ttfb, total, ips, colos = [], [], [], [], [], {}, {}
for i in range(50):
    try:
        t0 = time.perf_counter()
        ip = socket.getaddrinfo(HOST, 443, socket.AF_INET, socket.SOCK_STREAM)[0][4][0]
        t1 = time.perf_counter()
        s = socket.create_connection((ip, 443), timeout=10); s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        t2 = time.perf_counter()
        ss = ctx.wrap_socket(s, server_hostname=HOST)
        t3 = time.perf_counter()
        ss.sendall(b"GET /time HTTP/1.1\r\nHost: " + HOST.encode() + b"\r\nUser-Agent: latency-check\r\nConnection: close\r\n\r\n")
        first = ss.recv(1)
        t4 = time.perf_counter()
        rest = first
        while True:
            chunk = ss.recv(65536)
            if not chunk: break
            rest += chunk
        if i == 0: out["tls_version"] = ss.version()
        ss.close()
        dns.append((t1 - t0) * 1000); tcp.append((t2 - t1) * 1000); tls.append((t3 - t2) * 1000); ttfb.append((t4 - t3) * 1000); total.append((t4 - t0) * 1000)
        ips[ip] = ips.get(ip, 0) + 1
        for line in rest.split(b"\r\n"):
            if line.lower().startswith(b"cf-ray:"):
                colo = line.decode().rsplit("-", 1)[-1].strip(); colos[colo] = colos.get(colo, 0) + 1
    except Exception as e:
        out.setdefault("cold_errors", []).append(repr(e))
    time.sleep(0.2)
out["cold"] = {"dns": stats(dns), "tcp_connect": stats(tcp), "tls_handshake": stats(tls), "request_to_first_byte": stats(ttfb), "total_to_first_byte": stats(total), "resolved_ips": ips, "cloudflare_colo": colos}

# Warm connection: one keep-alive connection, three request types in rotation.
reqs = [("GET /time", "GET", "/time", None)]
if token: reqs.append(("GET /book", "GET", "/book?token_id=" + token, None))
reqs.append(("POST /order (unsigned, rejected)", "POST", "/order", b"{}"))
samples = {r[0]: [] for r in reqs}; codes = {r[0]: {} for r in reqs}; sizes = {r[0]: [] for r in reqs}
reconnects = 0; errors = []; first_bodies = {}; warm_colos = {}
def connect():
    c = http.client.HTTPSConnection(HOST, timeout=10, context=ctx); c.connect()
    c.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
    return c
conn = connect()
ROUNDS = 520
w0 = time.time()
for i in range(ROUNDS):
    for name, method, path, body in reqs:
        headers = {"User-Agent": "latency-check"}
        if body is not None: headers["Content-Type"] = "application/json"
        try:
            t0 = time.perf_counter()
            conn.request(method, path, body=body, headers=headers)
            resp = conn.getresponse(); data = resp.read()
            dt = (time.perf_counter() - t0) * 1000
            if i >= 20:  # first 20 rounds warm up the connection and are discarded
                samples[name].append(dt); codes[name][resp.status] = codes[name].get(resp.status, 0) + 1; sizes[name].append(len(data))
                colo = (resp.getheader("cf-ray") or "").rsplit("-", 1)[-1]; warm_colos[colo] = warm_colos.get(colo, 0) + 1
            if name not in first_bodies:
                first_bodies[name] = {"status": resp.status, "body": data[:200].decode("utf-8", "replace"), "headers": {k: v for k, v in resp.getheaders() if k.lower() in ("server", "cf-ray", "cf-cache-status", "content-type", "retry-after")}}
        except Exception as e:
            errors.append(name + ": " + repr(e)); reconnects += 1
            try: conn.close()
            except Exception: pass
            time.sleep(0.5); conn = connect()
        time.sleep(0.05)
out["warm"] = {name: dict(stats(v), status_codes=codes[name], median_body_bytes=int(statistics.median(sizes[name]))) for name, v in samples.items() if v}
out["warm_meta"] = {"rounds_measured": ROUNDS - 20, "rounds_discarded": 20, "duration_s": round(time.time() - w0, 1), "reconnects": reconnects, "errors": errors[:10], "cloudflare_colo": warm_colos, "first_responses": first_bodies}
out["finished_utc"] = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
print(json.dumps(out))
