#!/usr/bin/env python3
"""DAS: uji akhir — kirim event + klik tombol, tangkap isi permintaan dengan benar."""
import asyncio, json

UJI = "https://dasindonesia.com/bengkel-mercy-surabaya/"


async def main():
    from playwright.async_api import async_playwright
    tertangkap = []
    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 Chrome/124 Safari/537.36")

        async def sadap(route, request):
            if "collect" in request.url:
                isi = request.post_data
                if isi is None:
                    try:
                        buf = request.post_data_buffer
                        isi = buf.decode("utf-8", "replace") if isinstance(buf, (bytes, bytearray)) else None
                    except Exception:
                        isi = None
                tertangkap.append({"u": request.url, "body": isi})
            await route.continue_()

        await ctx.route("**/*collect*", sadap)
        hal = await ctx.new_page()
        await hal.goto(UJI, wait_until="domcontentloaded", timeout=180000)
        await hal.wait_for_timeout(9000)
        await hal.evaluate("window.gtag('event','uji_manual',{'transport_type':'beacon'})")
        await hal.wait_for_timeout(4000)
        await hal.evaluate("""
            const t = document.querySelectorAll("a[onclick*='klik_wa']");
            if (t.length) { t[0].setAttribute('target','_blank'); t[0].click(); }
        """)
        await hal.wait_for_timeout(12000)
        await br.close()

    print(f"total permintaan collect: {len(tertangkap)}")
    for i, x in enumerate(tertangkap):
        gab = (x["u"] or "") + " " + (x["body"] or "")
        tanda = "✅" if ("uji_manual" in gab or "klik_wa" in gab) else "  "
        print(f"   {tanda}[{i}] {(x['body'] or '(tanpa badan)')[:200]}")
        if x["body"] and "en=" in (x["body"] or ""):
            import re
            print(f"        en = {re.findall(r'en=[^&]*', x['body'])}")


asyncio.run(main())
