#!/usr/bin/env python3
"""Cek fakta #3313 tahap 3 - pasal spesifik UU 30/1999 (teks PDF BPK) + Perma 1/2016 + KUHPerdata."""
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"\(([^()\\]{2,})\)", d):
            hasil.append(m.group(1).decode("latin-1", "replace"))
    return re.sub(r"\s+", " ", " ".join(hasil))


def padat(t):
    return re.sub(r"\s+", "", t)


def cari_pasal(t, nomor, panjang=700):
    c = padat(t)
    for m in re.finditer(rf"Pasal{nomor}\b|Pasal{nomor}[A-Z]", c):
        # hindari rujukan silang: ambil hanya bila diikuti angka ayat/kata kunci
        seg = c[m.start():m.start() + panjang]
        print(f"  [{nomor}] {seg}")
        return True
    print(f"  [Pasal {nomor}] tidak ketemu")
    return False


# --- UU 30/1999 ---
st, b = get("https://peraturan.bpk.go.id/Download/158596/UU_1999_30.pdf")
t30 = pdf_text(b)
print(f"=== UU 30/1999 HTTP {st}, teks {len(t30)}")
for n in ("1", "3", "5", "11", "59", "60", "70"):
    print(f"\n-- Pasal {n}")
    cari_pasal(t30, n)

# --- Perma 1/2016 ---
for u in ("https://peraturan.bpk.go.id/Download/209641/Perma%20Nomor%201%20Tahun%202016.pdf",
          "https://peraturan.bpk.go.id/Download/209641"):
    st, b = get(u)
    print(f"\n=== Perma 1/2016 {u} -> HTTP {st} {len(b)}B")
    if st == 200 and b[:4] == b"%PDF":
        tp = pdf_text(b)
        print(f"    teks {len(tp)}")
        for n in ("4", "6", "7", "17", "18", "24"):
            print(f"\n-- Perma Pasal {n}")
            cari_pasal(tp, n)
        break

# --- KUHPerdata 1338 & 1243 dari situs pengadilan ---
for u, lab, pola in [
    ("https://www.pn-tanahgrogot.go.id/pilar-hukum-perikatan-memahami-fungsi-dan-pentingnya-pasal-1338-kuhperdata/",
     "PN Tanah Grogot - Pasal 1338", [r"Pasal 1338", r"undang-undang bagi", r"itikad baik"]),
    ("https://www.ilslawfirm.co.id/wanprestasi-pasal-1243-kuh-perdata/", "Pasal 1243 (firma hukum)",
     [r"Pasal 1243", r"penggantian biaya", r"bunga"]),
]:
    st, b = get(u)
    print(f"\n=== {lab} -> HTTP {st} {len(b)}B")
    if st == 200 and b:
        t = teks(b)
        for p in pola:
            m = re.search(p, t, re.I)
            if m:
                print(f"  [{p}] ...{t[max(0,m.start()-160):m.start()+520]}...")
            else:
                print(f"  [{p}] TIDAK DITEMUKAN")
