#!/usr/bin/env python3
import json, sys, urllib.request
import websocket

PORT = 9241
with urllib.request.urlopen(f"http://127.0.0.1:{PORT}/json/list", timeout=10) as r:
    targets = [t for t in json.loads(r.read().decode()) if t.get("type") == "page"]
for t in targets:
    print("PAGE:", t.get("title", "")[:60], "|", t.get("url", "")[:110])
# attach to the gainfix page if present, else first
cand = [t for t in targets if "gainfix" in t.get("url", "")] or targets[:1]
if not cand:
    sys.exit(0)
ws = websocket.create_connection(cand[0]["webSocketDebuggerUrl"], timeout=15)
_id = [0]
def send(method, **params):
    _id[0] += 1
    ws.send(json.dumps({"id": _id[0], "method": method, "params": params}))
    while True:
        msg = json.loads(ws.recv())
        if msg.get("id") == _id[0]:
            return msg.get("result", {})
expr = ("(()=>{var c=document.querySelector('#unity-canvas')||document.querySelector('canvas');"
        "var res=performance.getEntriesByType('resource').filter(r=>/WebGLTrial|index/.test(r.name)).map(r=>r.name.split('/').pop()+':'+Math.round(r.duration)+'ms:'+(r.transferSize||0));"
        "return JSON.stringify({ready:document.readyState,canvas:!!c,cw:c?c.width:0,ch:c?c.height:0,res:res,"
        "warn:(document.querySelector('#unity-warning')||{innerText:''}).innerText.slice(0,300)})})()")
r = send("Runtime.evaluate", expression=expr, returnByValue=True)
print("STATE:", r.get("result", {}).get("value"))
ws.close()
