#!/usr/bin/env python3
"""Ambil teks pasal spesifik: UU 18/2003 Pasal 16/18/19 (BPK + PERADI) dan UU ITE Pasal 5 (Komdigi UU 1/2024)."""
import re, 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 teks(u):
    try:
        with urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=90) as x:
            b = x.read(3000000)
    except urllib.error.HTTPError as e:
        return f"HTTP {e.code}"
    except Exception as e:
        return f"ERR {str(e)[:70]}"
    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).replace("&amp;", "&").replace("&#8217;", "'").replace("&quot;", '"')
    return re.sub(r"\s+", " ", t).strip()


def pasal(t, nomor, lebar=700):
    m = re.search(rf"Pasal {nomor}\s", t)
    if not m:
        print(f"  [Pasal {nomor} tidak ditemukan]")
        return
    print(f"  Pasal {nomor}: {t[m.start():m.start()+lebar]}")


for u, tag in [("https://peraturan.bpk.go.id/Details/43018/uu-no-18-tahun-2003", "BPK UU18/2003"),
               ("https://www.pbhperadi.or.id/undang-undang-no-18-tahun-2003/", "PERADI UU18/2003")]:
    t = teks(u)
    print(f"\n===== {tag} :: {len(t)} char")
    print("  awal:", t[:150])
    if len(t) < 800:
        continue
    for n in (16, 18, 19):
        pasal(t, n)

t = teks("https://jdih.komdigi.go.id/produk_hukum/view/id/884/t/undangundang+nomor+1+tahun+2024")
print(f"\n===== Komdigi UU 1/2024 :: {len(t)} char")
print("  awal:", t[:150])
if len(t) > 800:
    for n in (5,):
        pasal(t, n)
