#!/usr/bin/env python3
"""Quick CDP check: read root innerHTML"""
import json
import urllib.request
from websocket import create_connection

req = urllib.request.Request('http://127.0.0.1:9225/json/list')
resp = json.loads(urllib.request.urlopen(req, timeout=5))
ws_url = None
for p in resp:
    if 'localhost:5199' in p.get('url', ''):
        ws_url = p['webSocketDebuggerUrl']
        break

if not ws_url:
    print("No page found!")
    exit(1)

ws = create_connection(ws_url, timeout=10)

def cdp(method, params, msg_id):
    payload = json.dumps({"id": msg_id, "method": method, "params": params})
    ws.send(payload)

def recv_id(tid, timeout=3):
    ws.settimeout(timeout)
    while True:
        try:
            m = json.loads(ws.recv())
            if m.get("id") == tid:
                return m.get("result", {})
        except Exception:
            return None

cdp("Runtime.enable", {}, 1)
recv_id(1)

# Get root innerHTML
cdp("Runtime.evaluate", {"expression": "document.getElementById('root').innerHTML.substring(0, 1000)", "returnByValue": True}, 10)
r = recv_id(10)
if r:
    html = r.get("result", {}).get("value", "null")
    print("=== Root innerHTML (前1000字符) ===")
    print(html)
else:
    print("No result")

# Root child count
cdp("Runtime.evaluate", {"expression": "document.getElementById('root').children.length", "returnByValue": True}, 11)
r = recv_id(11)
val = r.get("result", {}).get("value", "?") if r else "?"
print("\nRoot children:", val)

ws.close()
