#!/usr/bin/env python3
"""Mikro-diagnosa: apakah push kena, dan container versi mana yang diunduh browser."""
import asyncio, json, sys, time, urllib.request, websockets

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


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)

        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(10)
        for jenis, extra in [("mouseMoved", {}), ("mouseWheel", {"deltaY": 400}), ("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(0.8)
        await asyncio.sleep(4)

        print("ukuran container yang diunduh:")
        print(" ", await ev("JSON.stringify(performance.getEntriesByType('resource').filter(function(r){return /gtm\\.js|gtag\\/js/.test(r.name);}).map(function(r){return r.name.split('?')[0].slice(-30)+' size='+r.transferSize;}))"))
        print("panjang dataLayer sebelum:", await ev("(window.dataLayer||[]).length"))
        print("push →", await ev("(function(){window.dataLayer.push({event:'manual_event_contact',x:1});return 'ok';})()"))
        await asyncio.sleep(2)
        print("panjang dataLayer sesudah:", await ev("(window.dataLayer||[]).length"))
        print("3 entri terakhir:", await ev("JSON.stringify((window.dataLayer||[]).slice(-3))"))
        print("dataLayer GTM internal:", await ev("(function(){try{var g=window.google_tag_manager['GTM-WQX6PGNR'];return g?JSON.stringify(Object.keys(g)):'tidak ada';}catch(e){return 'err '+e.message;}})()"))
        rt.cancel()


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