#!/usr/bin/env python3
"""Probe collect beacon GA4 untuk leitsurabaya.com — attach ke Chromium yang sudah jalan di port 9461."""
import asyncio, json, sys, time, urllib.request, websockets

PORT = int(sys.argv[2]) if len(sys.argv) > 2 else 9461
TARGET = sys.argv[1] if len(sys.argv) > 1 else "https://www.leitsurabaya.com/"


def open_tab():
    req = urllib.request.Request(f"http://127.0.0.1:{PORT}/json/new?about:blank", method="PUT")
    for _ in range(10):
        try:
            return json.load(urllib.request.urlopen(req, timeout=3))
        except Exception:
            time.sleep(0.5)
    raise RuntimeError("tab create failed")


hits = []


async def main():
    tab = open_tab()
    async with websockets.connect(tab["webSocketDebuggerUrl"], max_size=2**24) as ws:
        pending, mid = {}, 0

        async def reader():
            async for raw in ws:
                msg = json.loads(raw)
                if "id" in msg and msg["id"] in pending:
                    pending[msg["id"]].set_result(msg)
                elif msg.get("method") == "Network.requestWillBeSent":
                    u = msg["params"]["request"]["url"]
                    if any(k in u for k in ["googletagmanager", "google-analytics", "collect",
                                            "analytics.google", "region1.google-analytics"]):
                        hits.append(u)

        rtask = asyncio.create_task(reader())

        async def cmd(method, params=None):
            nonlocal mid
            mid += 1
            fut = asyncio.get_event_loop().create_future()
            pending[mid] = fut
            await ws.send(json.dumps({"id": mid, "method": method, "params": params or {}}))
            return await asyncio.wait_for(fut, 30)

        await cmd("Page.enable"); await cmd("Network.enable"); await cmd("Runtime.enable")
        await cmd("Page.navigate", {"url": TARGET})
        await asyncio.sleep(9)
        for ev, extra in [("mouseMoved", {}), ("mouseWheel", {"deltaY": 700}),
                          ("mousePressed", {"button": "left", "clickCount": 1}),
                          ("mouseReleased", {"button": "left", "clickCount": 1})]:
            p = {"x": 350, "y": 350}; p.update(extra)
            await cmd("Input.dispatchMouseEvent", {"type": ev, **p})
            await asyncio.sleep(0.8)
        await asyncio.sleep(10)
        expr = """JSON.stringify({
          rocket: document.querySelectorAll('script[type=rocketlazyloadscript]').length,
          gtm_loaded: !!document.querySelector('script[src*=googletagmanager]'),
          gtag_fn: typeof window.gtag==='function',
          dl_len: (window.dataLayer||[]).length,
          tid: (window.dataLayer||[]).map(e=>JSON.stringify(e)).filter(s=>s.includes('G-')||s.includes('GT-')).slice(0,4)
        })"""
        chk = await cmd("Runtime.evaluate", {"expression": expr, "returnByValue": True})
        print("DOM:", chk.get("result", {}).get("result", {}).get("value"))
        print("NETWORK HITS (%d):" % len(hits))
        for h in hits[:15]:
            print("  ", h[:150])
        print("collect beacon:", sum(1 for h in hits if "collect" in h or "region1.google-analytics" in h))
        rtask.cancel()


try:
    asyncio.run(main())
except Exception as e:
    print("ERR", type(e).__name__, str(e)[:300])
