# -*- coding: utf-8 -*-
"""分析 Choose File 按钮周围的 DOM 结构"""
import sys, socket, json
sys.stdout.reconfigure(encoding="utf-8")

HOST = "localhost"
PORT = 28800
PAGE_ID = "70039F329097C14448996F189E3A42A1"

def make_ws():
    import urllib.parse
    u = "ws://%s:%s/devtools/page/%s" % (HOST, PORT, PAGE_ID)
    p = urllib.parse.urlparse(u)
    s = socket.create_connection((p.hostname, p.port or 80), timeout=15)
    req = (
        "GET %s HTTP/1.1\r\nHost: %s:%s\r\nUpgrade: websocket\r\n"
        "Connection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
        "Sec-WebSocket-Version: 13\r\n\r\n"
    ) % (p.path, p.hostname, p.port)
    s.send(req.encode())
    resp = b""
    while b"\r\n\r\n" not in resp:
        resp += s.recv(4096)
    return s

def ws_send(sock, data):
    data = data.encode("utf-8")
    n = len(data)
    m = b"\x01\x02\x03\x04"
    if n <= 125:
        h = bytes([0x81, n | 0x80]) + m
    elif n <= 65535:
        h = bytes([0x81, 0xFE]) + n.to_bytes(2, "big") + m
    else:
        h = bytes([0x81, 0xFF]) + n.to_bytes(8, "big") + m
    sock.send(h + bytes(data[i] ^ m[i % 4] for i in range(n)))

def ws_recv(sock):
    h = b""
    while len(h) < 2:
        h += sock.recv(2 - len(h))
    n = h[1] & 0x7F
    if n == 126:
        nb = b""
        while len(nb) < 2:
            nb += sock.recv(2 - len(nb))
        n = int.from_bytes(nb, "big")
    elif n == 127:
        nb = b""
        while len(nb) < 8:
            nb += sock.recv(8 - len(nb))
        n = int.from_bytes(nb, "big")
    body = b""
    while len(body) < n:
        body += sock.recv(n - len(body))
    return body.decode("utf-8")

_mid = [0]

def cdp(sock, method, params=None):
    if params is None:
        params = {}
    _mid[0] += 1
    ws_send(sock, json.dumps({"id": _mid[0], "method": method, "params": params}))
    sock.settimeout(20)
    for _ in range(300):
        try:
            r = json.loads(ws_recv(sock))
            if r.get("id") == _mid[0]:
                return r
        except Exception:
            pass
    return None

sock = make_ws()
print("[OK] Connected\n")

# 分析 Choose File 区域的完整 HTML
r = cdp(sock, "Runtime.evaluate", {
    "expression": """
    (function() {
        // 找到包含 "Choose File" 文字的元素
        var all = document.querySelectorAll('button, span, div, label');
        var target = null;
        for (var el of all) {
            if (el.textContent.trim().indexOf('Choose File') > -1 && el.children.length === 0) {
                target = el;
                break;
            }
        }
        if (!target) return 'Choose File not found';
        
        // 获取其父元素的 HTML
        var parent = target.parentElement;
        if (!parent) return 'no parent';
        // 往上找到包含封面上传区域的容器
        for (var i = 0; i < 5; i++) {
            if (parent.parentElement) parent = parent.parentElement;
        }
        // 只返回前 3000 字符
        return parent.outerHTML.substring(0, 3000);
    })()
    """,
    "returnByValue": True
})
val = r.get("result", {}).get("result", {}).get("value", "") if r else ""
print("Cover area HTML:")
print(val)

# 也获取 "选择封面" 按钮的 HTML
r = cdp(sock, "Runtime.evaluate", {
    "expression": """
    (function() {
        var all = document.querySelectorAll('*');
        for (var el of all) {
            var t = (el.textContent || '').trim();
            if (t === '选择封面' || t.indexOf('选择封面') === 0) {
                if (el.children.length === 0) {
                    var p = el.parentElement;
                    // 检查 p 的 onclick 和事件监听
                    var onclick = p.getAttribute('onclick') || '';
                    var pClass = (p.className || '').substring(0, 50);
                    var pTag = p.tagName;
                    var ppHTML = p.parentElement ? p.parentElement.outerHTML.substring(0, 500) : '';
                    return JSON.stringify({
                        elTag: el.tagName,
                        parentTag: pTag,
                        parentClass: pClass,
                        onclick: onclick,
                        parentHTML: ppHTML
                    });
                }
            }
        }
        return 'not found';
    })()
    """,
    "returnByValue": True
})
val = r.get("result", {}).get("result", {}).get("value", "") if r else ""
print("\n选择封面 button:")
print(val)

sock.close()
print("\nDone")
