#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Verifikasi HTTP dari LUAR (check-host.net) untuk banyak URL sekaligus — submit paralel, poll bareng.

Pakai: python3 verif_luar_batch_20261004.py
"""
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"}

URLS = [
    "https://studiosoft.id/bikin-konten-pakai-ai-boleh-asal-tahu-batasnya/",
    "https://studiosoft.id/tools-ai-untuk-bisnis-pilih-sesuai-kebutuhan/",
    "https://www.theskincodeclinic.com/cara-mencegah-penularan-pms-3/",
    "https://www.theskincodeclinic.com/fak-penting-kutil-kelamin-hpv-3/",
    "https://dasindonesia.com/hal-wajib-cek-sebelum-beli-mobil-listrik-bekas/",
    "https://dasindonesia.com/tips-merawat-mobil-ev-das-bengkel-indonesia/",
]

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"))

pend = {}
for u in URLS:
    q = "https://check-host.net/check-http?host=%s&max_nodes=4" % urllib.parse.quote(u, safe="")
    try:
        rid = get(q).get("request_id")
        pend[rid] = {"url": u, "codes": set(), "nodes": 0, "done": False}
        print(f"submit {u} -> {rid}", flush=True)
    except Exception as e:
        print(f"submit GAGAL {u}: {e}", flush=True)
    time.sleep(1)

waited = 0
while waited < 120 and any(not v["done"] for v in pend.values()):
    time.sleep(15)
    waited += 15
    for rid, st in pend.items():
        if st["done"]:
            continue
        try:
            res = get("https://check-host.net/check-result/%s" % rid)
        except Exception as e:
            print(f"  poll {rid} error {e}", flush=True)
            continue
        nodes = st["nodes"]
        codes = set()
        for node, v in res.items():
            if not v:
                continue
            nodes = max(nodes, 1)
            it = v[0] if isinstance(v, list) else v
            if isinstance(it, dict):
                codes.add(str(it.get("status_code") or it.get("error") or "?"))
        st["codes"] |= codes
        st["nodes"] = len(res)
        if any(c.startswith("2") for c in st["codes"]):
            st["done"] = True
        elif st["nodes"] and all(res.get(n) for n in res):
            st["done"] = True
    for rid, st in pend.items():
        print(f"  t+{waited}s {st['url']} -> {sorted(st['codes'])} nodes={st['nodes']}", flush=True)

print("\n=== HASIL ===")
ok = True
for rid, st in pend.items():
    good = any(c.startswith("2") for c in st["codes"])
    ok = ok and good
    print(("✅" if good else "❌") + f" {st['url']} -> {sorted(st['codes'])}")
sys.exit(0 if ok else 1)
