#!/usr/bin/env python3
"""Cek apakah artikel mediasi/arbitrase sudah ada di tslaw.id + survei cepat kondisi situs."""
import base64, json, urllib.request, urllib.error, time

DOM = "tslaw.id"
USER, PASS = "bambangbot", "EFKm EYGx VQCP Y9go ncPr uM2Y"
AUTH = base64.b64encode(f"{USER}:{PASS}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}


def rest(path, method="GET", data=None):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    body = None
    if data is not None:
        body = json.dumps(data).encode()
        h["Content-Type"] = "application/json"
    r = urllib.request.Request(f"https://{DOM}{path}", data=body, headers=h, method=method)
    with urllib.request.urlopen(r, timeout=60) as resp:
        return json.loads(resp.read().decode())


t0 = time.time()
try:
    posts = rest("/wp-json/wp/v2/posts?per_page=100&status=publish,future,draft&context=edit&_fields=id,slug,title,status,link,meta")
    print("API OK", round(time.time() - t0, 2), "s | total post:", len(posts))
except Exception as e:
    print("API GAGAL:", e)
    raise SystemExit(1)

cari = [p for p in posts if any(k in p["slug"] for k in ("mediasi", "arbitrase", "bani"))]
print("post bermuatan mediasi/arbitrase:", [(p["id"], p["slug"], p["status"]) for p in cari])
terakhir = sorted(posts, key=lambda p: p["id"], reverse=True)[:6]
for p in terakhir:
    print(" terbaru:", p["id"], p["status"], p["slug"], p["title"]["raw"][:70])
idmax = max(p["id"] for p in posts)
print("id tertinggi:", idmax)
json.dump([{k: p[k] for k in ("id", "slug", "status", "link")} for p in posts], open("tslaw_listikel/_survei25.json", "w"))
