#!/usr/bin/env python3
"""Rekam SEMUA permintaan ke kolektor GA4 (termasuk POST + isi body) saat tombol WhatsApp diklik."""
import asyncio, json, sys, time, urllib.request, websockets

PORT = int(sys.argv[2]) if len(sys.argv) > 2 else 9481
TARGET = sys.argv[1] if len(sys.argv) > 1 else "https://studiosoft.id/"
rekam = []


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


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

        async def reader():
            async for raw in ws:
                m = json.loads(raw)
                if "id" in m and m["id"] in pending:
                    pending[m["id"]].set_result(m)
                elif m.get("method") == "Network.requestWillBeSent":
                    r = m["params"]["request"]
                    u = r["url"]
                    if "collect" in u or "analytics.google" in u or "doubleclick" in u:
                        rekam.append({"method": r.get("method"), "url": u, "post": r.get("postData", "")})

        rt = asyncio.create_task(reader())

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

        async def ev(x):
            r = await cmd("Runtime.evaluate", {"expression": x, "returnByValue": True})
            return r.get("result", {}).get("result", {}).get("value")

        await cmd("Page.enable"); await cmd("Network.enable"); await cmd("Runtime.enable")
        await cmd("Page.navigate", {"url": TARGET})
        await asyncio.sleep(8)
        for jenis, extra in [("mouseMoved", {}), ("mouseWheel", {"deltaY": 500}), ("mousePressed", {"button": "left", "clickCount": 1}), ("mouseReleased", {"button": "left", "clickCount": 1})]:
            p = {"x": 400, "y": 300}; p.update(extra)
            await cmd("Input.dispatchMouseEvent", {"type": jenis, **p})
            await asyncio.sleep(1)
        await asyncio.sleep(6)
        rekam.clear()

        klik = await ev("""(function(){var a=document.querySelector('a[href*="wa.me"],a[href*="whatsapp"]');
            if(!a) return 'tidak ada link';
            a.dispatchEvent(new MouseEvent('click',{bubbles:true,cancelable:true,view:window}));
            return 'klik: '+(a.getAttribute('href')||'').slice(0,50);})()""")
        print("aksi:", klik)
        await asyncio.sleep(10)

        print(f"\npermintaan ke kolektor: {len(rekam)}")
        for r in rekam:
            en = ""
            if "en=" in r["url"]:
                en = r["url"].split("en=")[1].split("&")[0]
            elif "manual_event_CONTACT" in (r["post"] or ""):
                en = "manual_event_CONTACT (di body POST)"
            elif "qualify_lead" in (r["post"] or ""):
                en = "qualify_lead (di body POST)"
            print(f"  {r['method']:<5} event={en or '(page_view/auto)':<34} body={len(r['post'] or '')} byte")
            print(f"        {r['url'][:130]}")
            if r["post"]:
                print(f"        BODY: {(r['post'] or '')[:200]}")
        rt.cancel()


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