#!/usr/bin/env python3
"""Ambil teks resmi Pasal 433-436 UU 1/2023 (KUHP) + Pasal 27A/45 ayat (4) UU ITE pasca UU 1/2024."""
import re, urllib.request, urllib.error, zlib

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}


def unduh(u):
    with urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=180) as x:
        return x.read()


def pdf_teks(b):
    out = []
    for m in re.finditer(rb"stream\r?\n(.*?)endstream", b, re.S):
        s = m.group(1)
        try:
            d = zlib.decompress(s)
        except Exception:
            continue
        if b"Tj" not in d and b"TJ" not in d:
            continue
        # ambil string dalam (...) atau <hex>
        teks = []
        for mm in re.finditer(rb"\((?:\\.|[^\\()])*\)|<[0-9A-Fa-f\s]+>", d):
            g = mm.group(0)
            if g.startswith(b"("):
                t = g[1:-1]
                t = re.sub(rb"\\([()\\])", rb"\1", t)
                teks.append(t.decode("latin-1", "replace"))
            else:
                h = re.sub(rb"\s", b"", g[1:-1])
                try:
                    teks.append(bytes.fromhex(h.decode()).decode("latin-1", "replace"))
                except Exception:
                    pass
        out.append(" ".join(teks))
    return "\n".join(out)


print("=== UU 1/2023 KUHP dari BPK")
url = "https://peraturan.bpk.go.id/Download/287456/UU%20Nomor%201%20Tahun%202023.pdf"
try:
    b = unduh(url)
    print("  bytes", len(b))
    t = pdf_teks(b)
    print("  teks", len(t))
    t2 = re.sub(r"\s+", " ", t)
    for pat in [r"Pasal 433", r"Pasal 434", r"Pasal 435", r"Pasal 436"]:
        for m in list(re.finditer(pat, t2))[:2]:
            print(f"\n  [{pat}] ...{t2[m.start():m.start()+650]}...")
except Exception as e:
    print("  ERR", str(e)[:150])
