#!/usr/bin/env python3
"""Verifikasi HTTP 200 dari LUAR (check-host.net): poll max 90 s, lapor kalau ada node balas 200.

Catatan: origin situs klien sedang lambat (~20-25 s per halaman yang belum ter-cache Cloudflare),
jadi WAJIB tunggu — timeout 25 s di node sering muncul walau halaman sebenarnya 200.

Usage: python3 verif_200_luar.py <url> [...]
Exit 0 kalau semua URL 200.
"""
import json, sys, time, urllib.parse, urllib.request

UA = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) Chrome/124 Safari/537.36", "Accept": "application/json"}


def get(url, timeout=90):
    req = urllib.request.Request(url, headers=UA)
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.loads(r.read().decode("utf-8", "replace"))


def verif(u, nodes=4, max_wait=90):
    q = "https://check-host.net/check-http?host=%s&max_nodes=%d" % (urllib.parse.quote(u, safe=""), nodes)
    rid = get(q).get("request_id")
    if not rid:
        return False, "no request_id"
    codes = []
    waited = 0
    while waited < max_wait:
        time.sleep(15)
        waited += 15
        res = get("https://check-host.net/check-result/%s" % rid)
        codes = []
        for node, v in res.items():
            if not v:
                continue
            it = v[0] if isinstance(v, list) else v
            if isinstance(it, dict):
                codes.append(str(it.get("status_code") or it.get("error") or "?"))
        if any(c.startswith("200") for c in codes):
            return True, "200 (%s) t+%ds" % (", ".join(sorted(set(codes))), waited)
        if len(codes) >= nodes:
            break
    return False, ", ".join(sorted(set(codes))) or "kosong"


if __name__ == "__main__":
    ok_all = True
    for u in sys.argv[1:]:
        ok, info = verif(u)
        ok_all = ok_all and ok
        print("%s %s -> %s" % ("✅" if ok else "❌", u, info))
    sys.exit(0 if ok_all else 1)
