#!/usr/bin/env python3
"""Cari jejak PT Sampoerna Jaya Baja dengan peramban sungguhan (hasil mesin pencari + peta)."""
import asyncio, json, re, sys

TANYA = [
    ("google", 'PT Sampoerna Jaya Baja Bekasi'),
    ("google", '"Sampoerna Jaya Baja" baja'),
    ("ddg", '"Sampoerna Jaya Baja"'),
    ("maps", 'Sampoerna Jaya Baja Bekasi'),
]


async def jalan():
    from playwright.async_api import async_playwright
    hasil = {}
    async with async_playwright() as pw:
        br = await pw.chromium.launch()
        ctx = await br.new_context(user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36",
                                   locale="id-ID", viewport={"width": 1366, "height": 900})
        hal = await ctx.new_page()

        for mesin, q in TANYA:
            if mesin == "google":
                u = "https://www.google.com/search?hl=id&gl=id&num=20&q=" + q.replace(" ", "+").replace('"', "%22")
            elif mesin == "ddg":
                u = "https://duckduckgo.com/?kl=id-id&q=" + q.replace(" ", "+").replace('"', "%22")
            else:
                u = "https://www.google.com/maps/search/" + q.replace(" ", "+")
            print(f"\n=== {mesin.upper()}: {q} ===")
            try:
                await hal.goto(u, wait_until="domcontentloaded", timeout=90000)
                await hal.wait_for_timeout(6000)
                isi = await hal.content()
                # hasil pencarian
                blok = await hal.query_selector_all("div.g, div[data-sokoban-container], article, div.result, div[data-testid='result']")
                cocok = 0
                for b in blok[:12]:
                    try:
                        teks = (await b.inner_text())[:400].replace("\n", " | ")
                        tautan = await b.query_selector("a")
                        href = await tautan.get_attribute("href") if tautan else ""
                        if "sampoerna" in teks.lower() or "baja" in teks.lower():
                            cocok += 1
                            print(f"   » {teks[:300]}")
                            if href:
                                print(f"     {href[:120]}")
                    except Exception:
                        continue
                if cocok == 0:
                    bersih = re.sub(r"<[^>]+>", " ", isi)
                    sebut = re.findall(r".{0,120}Sampoerna Jaya Baja.{0,160}", bersih, re.I)
                    print(f"   (tidak ada blok hasil yang memuat nama; sebutan di halaman: {len(re.findall('sampoerna jaya baja', bersih, re.I))})")
                    for s in sebut[:3]:
                        print("   »", re.sub(r"\s+", " ", s)[:280])
            except Exception as e:
                print("   gagal:", str(e)[:120])

        # AHU: cari daftar badan hukum
        print("\n=== AHU (Ditjen Administrasi Hukum Umum) ===")
        try:
            await hal.goto("https://ahu.go.id/pencarian/profil-badan", wait_until="domcontentloaded", timeout=90000)
            await hal.wait_for_timeout(5000)
            isi = await hal.inner_text("body")
            print("   judul halaman:", (await hal.title())[:90])
            print("   cuplikan:", re.sub(r"\s+", " ", isi)[:300])
        except Exception as e:
            print("   gagal:", str(e)[:120])

        await br.close()


asyncio.run(jalan())
