#!/usr/bin/env python3
"""TSLaw: riset nama praktisi/lembaga hukum keluarga Surabaya yang benar-benar ada + cari foto Pexels."""
import base64, json, re, time, urllib.parse, 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 bing(q, hal=1):
    u = f"https://www.bing.com/search?q={urllib.parse.quote_plus(q)}&setlang=id&count=30&first={hal}"
    try:
        h = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=60).read().decode("utf-8", "replace")
        hasil = []
        for blok in re.findall(r'<li class="b_algo".*?</li>', h, re.S):
            m = re.search(r"<h2[^>]*>(.*?)</h2>", blok, re.S)
            if not m:
                continue
            judul = re.sub(r"<[^>]+>", "", m.group(1))
            tgt = re.search(r"[?&]u=a1([A-Za-z0-9_\-]+)", blok)
            dom = ""
            if tgt:
                s = tgt.group(1) + "=" * (-len(tgt.group(1)) % 4)
                try:
                    dom = urllib.parse.urlparse(base64.urlsafe_b64decode(s).decode("utf-8", "replace")).netloc
                except Exception:
                    dom = ""
            hasil.append((judul.strip()[:80], dom))
        return hasil
    except Exception as e:
        return [("gagal: " + str(e)[:50], "")]


print("=== pencarian: pengacara gugat cerai Surabaya ===")
for q in ("pengacara gugat cerai surabaya", "law firm hukum keluarga surabaya", "LBH APIK surabaya advokat"):
    print(f"\n  [{q}]")
    for judul, dom in bing(q)[:8]:
        print(f"     {judul:<82} {dom}")

print("\n\n=== foto Pexels ===")
for q in ("divorce", "last will testament"):
    enc = urllib.parse.quote(q)
    try:
        md = urllib.request.urlopen(urllib.request.Request(
            f"https://r.jina.ai/https://www.pexels.com/search/{enc}/", headers=UA), timeout=90).read().decode("utf-8", "replace")
        ids = []
        for m in re.finditer(r"pexels-photo-(\d{4,})", md):
            if m.group(1) not in ids:
                ids.append(m.group(1))
        print(f"  {q}: {ids[:10]}")
    except Exception as e:
        print(f"  {q}: gagal {str(e)[:60]}")
