import json, time, sys
from websocket import create_connection

# Get WebSocket URL from previous run
with open('/tmp/ws_url.txt') as f:
    ws_url = f.read().strip()

ws = create_connection(ws_url)

def send_cdp(method, params=None):
    msg = {"id": int(time.time()*1000), "method": method}
    if params:
        msg["params"] = params
    ws.send(json.dumps(msg))
    # Read response
    try:
        ws.settimeout(3)
        resp = ws.recv()
        return json.loads(resp)
    except:
        return None

# Enable Runtime
send_cdp("Runtime.enable")
time.sleep(0.5)

# Check if Portal div exists and has content
result = send_cdp("Runtime.evaluate", {
    "expression": """
    (function() {
        var root = document.getElementById('ghost-portal-root');
        var html = root ? root.innerHTML : 'NO_ROOT';
        var hash = window.location.hash;
        var portalScript = document.querySelector('script[src*=\"portal\"]');
        var portalSrc = portalScript ? portalScript.src : 'NO_SCRIPT';
        return JSON.stringify({
            portalRootHTML: html.substring(0, 300),
            hash: hash,
            portalSrc: portalSrc,
            title: document.title,
            bodyHasImg: document.body.innerHTML.includes('onerror')
        });
    })()
    """,
    "returnByValue": True
})

print(json.dumps(result, indent=2))
ws.close()
