# -*- coding: utf-8 -*-
"""用 CDP Page.setUploadFiles 上传封面图"""
import sys, socket, json, time, os, glob
sys.stdout.reconfigure(encoding='utf-8')

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

IMG_LIST = glob.glob(r"D:\wxpic\*.jpg") + glob.glob(r"D:\wxpic\*.png")
IMG_PATH = max(IMG_LIST, key=os.path.getmtime) if IMG_LIST else None
print("[INFO] 图片:", IMG_PATH)

# CDP WebSocket
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\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-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_n(sock, n):
    buf = b""
    while len(buf) < n:
        buf += sock.recv(n - len(buf))
    return buf

def ws_recv_msg(sock):
    h = ws_recv_n(sock, 2)
    n = h[1] & 0x7F
    if n == 126:
        n = int.from_bytes(ws_recv_n(sock, 2), "big")
    elif n == 127:
        n = int.from_bytes(ws_recv_n(sock, 8), "big")
    return ws_recv_n(sock, n).decode("utf-8")

_counter = [0]

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

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

# Step 1: DOM.getDocument
print("[Step 1] DOM.getDocument...")
r = cdp(sock, "DOM.getDocument", {"depth": 0})
root = r["result"]["root"]["nodeId"]
print("  root nodeId:", root)

# Step 2: querySelectorAll input[type=file]
print("\n[Step 2] querySelectorAll...")
r = cdp(sock, "DOM.querySelectorAll", {"nodeId": root, "selector": "input[type=file]"})
all_ids = r["result"]["nodeIds"]
print("  nodeIds:", all_ids)

# Step 3: 获取每个 input 的 accept 属性，找图片类型的
print("\n[Step 3] 获取 accept 属性...")
cover_node = None
for bId in all_ids:
    r = cdp(sock, "DOM.requestNode", {"backendNodeId": bId})
    nid = r["result"].get("node")
    if not nid:
        continue
    r = cdp(sock, "DOM.getAttributes", {"nodeId": nid})
    if r:
        attrs = r["result"]["attributes"]
        pairs = {}
        for i in range(0, len(attrs), 2):
            pairs[attrs[i]] = attrs[i + 1]
        accept = pairs.get("accept", "")
        print("  backendId=%d nodeId=%s accept=%s" % (bId, nid, accept))
        if "image" in accept and "video" not in accept and cover_node is None:
            cover_node = nid
            print("  -> 这是封面图!")

# Step 4: Page.setUploadFiles
if cover_node:
    print("\n[Step 4] Page.setUploadFiles nodeId=%s..." % cover_node)
    r = cdp(sock, "Page.setUploadFiles", {"nodeId": cover_node, "files": [IMG_PATH]})
    print("  结果:", r)

    if r and r.get("result") == {}:
        print("\n  文件已设置！等待上传处理（8秒）...")
        time.sleep(8)

        # 检查封面图
        r = cdp(sock, "Runtime.evaluate", {
            "expression": """
            (function() {
              var imgs = document.querySelectorAll("img");
              var r = [];
              for (var img of imgs) {
                var w = img.naturalWidth || img.width;
                var h = img.naturalHeight || img.height;
                var src = img.src || "";
                if (w > 50 && h > 50 && src.indexOf("vcg") === -1 && src.indexOf("copyright") === -1) {
                  r.push({w: w, h: h, src: src.substring(0, 50)});
                }
              }
              return JSON.stringify(r);
            })()
            """,
            "returnByValue": True
        })
        print("  封面图:", r.get("result", {}).get("result", {}).get("value", ""))
    else:
        print("  设置失败:", r)
else:
    print("  未找到封面图 input")

sock.close()
print("\n完成")
