#!/usr/bin/env python3
"""Cek fakta #3313 tahap 5 - konfirmasi resmi tambahan (BPHN UU30 PDF) + cari teks Perma 1/2016 yang terbaca."""
import json, re, zlib, urllib.request, urllib.error

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}
WS = "/home/mantapman/.hermes/profiles/atun/workspace"


def get(u, n=4000000):
    try:
        r = urllib.request.Request(u, headers=UA)
        with urllib.request.urlopen(r, timeout=90) as x:
            return x.status, x.read(n)
    except urllib.error.HTTPError as e:
        return e.code, b""
    except Exception as e:
        return type(e).__name__, b""


def pdf_text(b):
    hasil = []
    for c in re.findall(rb"stream\r?\n(.*?)endstream", b, re.S):
        try:
            d = zlib.decompress(c)
        except Exception:
            continue
        for m in re.finditer(rb"\(([^()\\]{2,})\)", d):
            hasil.append(m.group(1).decode("latin-1", "replace"))
    return re.sub(r"\s+", " ", " ".join(hasil))


st, b = get("https://bphn.go.id/data/documents/99uu030.pdf")
print(f"=== BPHN UU 30/1999 -> HTTP {st} {len(b)}B")
if st == 200 and b[:4] == b"%PDF":
    t = pdf_text(b)
    print(f"    teks {len(t)}")
    for n in ("60", "11", "3"):
        m = re.search(rf"Pasal {n}\b", t)
        print(f"  [Pasal {n}]", (t[m.start():m.start()+400] if m else "tidak ketemu"))

tok = json.load(open(f"{WS}/.serper_token.json"))
KEY = tok.get("api_key") or tok.get("key") or list(tok.values())[0]
for q in ["\"Pasal 4\" perma 1 tahun 2016 \"wajib\" mediasi teks lengkap",
          "perma 1 2016 pdf mediasi pasal 4 ayat 1 wajib diupayakan mediasi"]:
    req = urllib.request.Request("https://google.serper.dev/search",
                                data=json.dumps({"q": q, "gl": "id", "hl": "id", "num": 8}).encode(),
                                headers={"X-API-KEY": KEY, "Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=60) as r:
        d = json.load(r)
    print(f"\n=== serper: {q}")
    for o in d.get("organic", [])[:8]:
        print("  -", o.get("link"), "|", (o.get("title") or "")[:80])
