#!/usr/bin/env python3
"""Verifikasi lanjutan: UU 16/2011 (via JDIH BPK) + UU 48/2009 Pasal 56-57 — 16 Okt 2026."""
import 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"}


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 teks(b):
    t = b.decode("utf-8", "replace")
    t = re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", t, flags=re.S | re.I)
    t = re.sub(r"<[^>]+>", " ", t)
    t = re.sub(r"&nbsp;?", " ", t)
    t = re.sub(r"&amp;", "&", t)
    return re.sub(r"\s+", " ", t).strip()


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"\((?:[^()\\]|\\.)*\)", d):
            hasil.append(m.group(0)[1:-1].decode("latin-1", "replace"))
    return re.sub(r"\s+", " ", " ".join(hasil))


def tampil(t, pola, maks=700):
    for pat in pola:
        n = 0
        for m in re.finditer(re.escape(pat), t, re.I):
            a, z = max(0, m.start() - 100), min(len(t), m.start() + maks)
            print(f"  [{pat}] ...{t[a:z]}...")
            n += 1
            if n >= 1:
                break
        if n == 0:
            print(f"  [{pat}] TIDAK DITEMUKAN")


# --- cari PDF UU 16/2011 di halaman JDIH BPK
st, b = get("https://peraturan.bpk.go.id/Details/39234/uu-no-16-tahun-2011")
print(f"=== halaman JDIH UU 16/2011 → HTTP {st}, {len(b)} byte")
link = ""
if st == 200:
    html = b.decode("utf-8", "replace")
    cand = re.findall(r'href="(/Download/[^"]+\.pdf[^"]*)"', html, re.I)
    print("  kandidat unduhan:", cand[:3])
    if cand:
        link = "https://peraturan.bpk.go.id" + cand[0].replace("&amp;", "&")
    # judul & status
    t = teks(b)
    for pat in ["UU No. 16 Tahun 2011", "Bantuan Hukum", "Status", "Berlaku", "Mencabut"]:
        m = re.search(re.escape(pat), t, re.I)
        if m:
            print(f"  [{pat}] ...{t[m.start():m.start()+220]}...")

if link:
    st2, b2 = get(link)
    print(f"\n=== PDF UU 16/2011 ({link}) → HTTP {st2}, {len(b2)} byte")
    if st2 == 200:
        t = pdf_text(b2) if b2[:4] == b"%PDF" else teks(b2)
        print("  (teks", len(t), "karakter)")
        tampil(t, ["Pasal 4", "Pasal 5", "Pasal 7", "Pasal 14", "Pasal 16", "Pasal 19", "Pasal 20",
                   "terakreditasi", "orang atau kelompok orang miskin", "Anggaran Pendapatan"], 620)

# --- UU 48/2009 dari PDF Hukumonline (pasal 56 & 57)
st3, b3 = get("https://learning.hukumonline.com/wp-content/uploads/2022/11/UU_NO_48_2009-1.pdf")
print(f"\n=== UU 48/2009 (Hukumonline) → HTTP {st3}, {len(b3)} byte")
if st3 == 200:
    t = pdf_text(b3) if b3[:4] == b"%PDF" else teks(b3)
    print("  (teks", len(t), "karakter)")
    tampil(t, ["Pasal 56", "Pasal 57"], 620)
