#!/usr/bin/env python3
"""Cek fakta #3313 tahap 7 - Perma 1/2016 Pasal 4 ayat (2) + biaya mediasi, dan Keppres 34/1981."""
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 get(u, n=5000000):
    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 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 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)
    return re.sub(r"\s+", " ", re.sub(r"&nbsp;?", " ", t)).strip()


st, b = get("https://www.mahkamahagung.go.id/media/8757")
tp = pdf_text(b)
i = tp.find("Pasal 4 id-ID")
print("=== Perma 1/2016 Pasal 4 (utuh) ===")
print(tp[i:i + 1400])
for pat in ("Biaya Mediasi", "Pasal 6 ", "tidak dapat diadakan perdamaian", "Pasal 29", "Pasal 30"):
    m = re.search(re.escape(pat), tp)
    print(f"\n-- [{pat}]", (tp[max(0, m.start() - 150):m.start() + 600] if m else "tidak ketemu"))

st, b = get("https://peraturan.bpk.go.id/Details/66483/keppres-no-34-tahun-1981")
print(f"\n=== Keppres 34/1981 -> HTTP {st}")
if st == 200:
    t = teks(b)
    m = re.search(r"Judul", t)
    print(t[m.start():m.start() + 700] if m else t[:700])
