#!/usr/bin/env python3
"""Ekstrak pasal penting UU 30/1999 dan Perma 1/2016 dari teks resmi."""
import json, 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 ambil(u, batas=8000000):
    try:
        with urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=120) as x:
            return x.read(batas)
    except Exception as e:
        print("GAGAL", u, str(e)[:80])
        return b""


def bersih(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 = t.replace("&nbsp;", " ").replace("&#8217;", "'").replace("&amp;", "&")
    return re.sub(r"\s+", " ", t).strip()


def pdf_teks(b):
    out = []
    for m in re.finditer(rb"stream\r?\n(.*?)endstream", b, re.S):
        try:
            d = zlib.decompress(m.group(1))
        except Exception:
            continue
        pot = b""
        for tm in re.finditer(rb"\((?:\\.|[^\\()])*\)", d):
            pot += tm.group(0)[1:-1] + b" "
        out.append(pot.decode("latin-1", "replace"))
    return re.sub(r"\s+", " ", " ".join(out))


def pasal(t, nomor, lebar=900):
    for pola in (rf"Pasal {nomor} ", rf"Pasal {nomor}\(", rf"Pasal {nomor}\n"):
        m = re.search(pola, t)
        if m:
            print(f"\n--- Pasal {nomor}: {t[m.start():m.start()+lebar]}")
            return
    print(f"\n--- Pasal {nomor}: TIDAK DITEMUKAN")


print("=== UU 30/1999 (perpajakan.ddtc.co.id)")
t = bersih(ambil("https://perpajakan.ddtc.co.id/id/sumber-hukum/peraturan-pusat/undang-undang-30-tahun-1999"))
print("panjang:", len(t))
for n in (1, 2, 3, 4, 5, 6, 9, 11, 22, 31, 32, 48, 60, 70, 72):
    pasal(t, n)

print("\n\n=== PERMA 1/2016 PDF (BPK)")
b = ambil("https://peraturan.bpk.go.id/Download/209641/Perma%20Nomor%201%20Tahun%202016.pdf")
print("unduh:", len(b), "byte")
if b[:4] == b"%PDF":
    p = pdf_teks(b)
    print("teks PDF:", len(p))
    print(p[:600])
    for kata in ["30 (tiga puluh) hari", "hari kerja", "itikad baik", "Pasal 13", "Pasal 22", "Pasal 23",
                 "Pasal 24", "Pasal 29", "Pasal 4", "biaya mediasi", "tidak dapat diterima"]:
        for m in list(re.finditer(re.escape(kata), p, re.I))[:2]:
            print(f"\n[{kata}] ...{p[max(0,m.start()-250):m.start()+350]}...")
