#!/usr/bin/env python3
"""DAS: uji kirim event GA4 langsung dari halaman, sambil membaca isi permintaan lewat penyadapan rute."""
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 = None
                try:
                    isi = request.post_data
                    if isi is None:
                        buf = await request.post_data_buffer()
                        isi = buf.decode("utf-8", "replace") if buf else None
                except Exception as e:
                    isi = f"(gagal baca: {str(e)[:40]})"
                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(8000)
        print("   gtag:", await hal.evaluate("typeof window.gtag"))

        n0 = len(tertangkap)
        await hal.evaluate("window.gtag('event','uji_manual',{'transport_type':'beacon','keterangan':'uji dari terminal'})")
        await hal.wait_for_timeout(8000)
        print(f"   permintaan sebelum uji: {n0} → sesudah: {len(tertangkap)}")

        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(9000)
        print(f"   setelah klik tombol: {len(tertangkap)} permintaan")
        await br.close()

    print("\n=== isi permintaan ===")
    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['u'][:95]}")
        if x["body"]:
            print(f"        body: {x['body'][:220]}")


asyncio.run(main())
