#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Loop verifikasi link klien (4 Okt 2026): coba akses langsung + check-host.net, ulang tiap 3 menit.

Tulis hasil ke /tmp/verif_loop_20261004.log ; keluar begitu SEMUA target dapat 200 (atau timeout total).
"""
import json, subprocess, sys, time, urllib.parse, urllib.request

TARGETS = {
    "uky_ss": "https://studiosoft.id/bikin-konten-pakai-ai-boleh-asal-tahu-batasnya/",
    "tsc": "https://www.theskincodeclinic.com/cara-mencegah-penularan-pms-3/",
    "das": "https://dasindonesia.com/hal-wajib-cek-sebelum-beli-mobil-listrik-bekas/",
}
UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126 Safari/537.36"
LOG = "/tmp/verif_loop_20261004.log"
UA_H = {"User-Agent": UA, "Accept": "application/json"}


def log(msg):
    line = f"[{time.strftime('%H:%M:%S')}] {msg}"
    print(line, flush=True)
    with open(LOG, "a") as f:
        f.write(line + "\n")


def local(url, tmo=30):
    t0 = time.time()
    p = subprocess.run(["curl", "-4", "-s", "-o", "/dev/null", "-w", "%{http_code}",
                        "--max-time", str(tmo), "-A", UA, url], capture_output=True, text=True)
    return p.stdout.strip() or "000", time.time() - t0


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


def checkhost(url, nodes=6, max_wait=75):
    q = "https://check-host.net/check-http?host=%s&max_nodes=%d" % (urllib.parse.quote(url, safe=""), nodes)
    rid = get(q).get("request_id")
    if not rid:
        return {}
    waited, last = 0, {}
    while waited < max_wait:
        time.sleep(15)
        waited += 15
        try:
            res = get("https://check-host.net/check-result/%s" % rid)
        except Exception as e:
            log(f"    poll {rid} err {str(e)[:60]}")
            continue
        codes = {}
        for node, v in res.items():
            if not v:
                continue
            item = v[0] if isinstance(v, list) else v
            if isinstance(item, list) and len(item) >= 4:
                codes[node] = str(item[3]) if item[3] else str(item[2])
            elif isinstance(item, dict):
                codes[node] = str(item.get("status_code") or item.get("error") or "?")
            else:
                codes[node] = str(item)[:30]
        last = codes
        if any(c == "200" or c.startswith("200") for c in codes.values()):
            return codes
    return last


deadline = time.time() + 45 * 60
round_no = 0
ok = {}
while time.time() < deadline:
    round_no += 1
    log(f"===== putaran {round_no} =====")
    for name, url in TARGETS.items():
        if ok.get(name):
            continue
        code, secs = local(url)
        log(f"  {name} lokal curl -> {code} ({secs:.1f}s)")
        if code == "200":
            ok[name] = "local"
            log(f"  ✅ {name} 200 dari lokal")
            continue
        codes = checkhost(url)
        ringkas = ", ".join(f"{k.split('.')[0]}={v}" for k, v in sorted(codes.items()))
        log(f"  {name} check-host -> {ringkas}")
        if any(str(v).startswith("2") for v in codes.values()):
            ok[name] = "check-host"
            log(f"  ✅ {name} 200 dari luar")
    if len(ok) == len(TARGETS):
        log("SEMUA TARGET 200 — selesai.")
        break
    log(f"  ... istirahat 120 s (status: {ok})")
    time.sleep(120)

log(f"SELESAI. ok={ok}")
with open("/tmp/verif_loop_20261004.result.json", "w") as f:
    json.dump(ok, f, indent=1)
sys.exit(0 if len(ok) == len(TARGETS) else 1)
