# -*- coding: utf-8 -*-
"""点击选择封面按钮，并等待弹窗打开"""
import sys, socket, json, time, urllib.request
sys.stdout.reconfigure(encoding='utf-8')

HOST = "localhost"
PORT = 9222

def ws_connect(page_id):
    import urllib.parse
    ws_url = f"ws://{HOST}:{PORT}/devtools/page/{page_id}"
    parsed = urllib.parse.urlparse(ws_url)
    sock = socket.create_connection((parsed.hostname, parsed.port or 80), timeout=15)
    key = 'dGhlIHNhbXBsZSBub25jZQ=='
    handshake = (
        f'GET {parsed.path} HTTP/1.1\r\n'
        f'Host: {parsed.hostname}:{parsed.port}\r\n'
        'Upgrade: websocket\r\nConnection: Upgrade\r\n'
        f'Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n'
    )
    sock.send(handshake.encode())
    resp = b''
    while b'\r\n\r\n' not in resp:
        resp += sock.recv(4096)
    return sock

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

def recv_frame(sock):
    def rx(n):
        buf = b''
        while len(buf) < n:
            buf += sock.recv(n - len(buf))
        return buf
    h = rx(2)
    n = h[1] & 0x7f
    if n == 126:
        n = int.from_bytes(rx(2), 'big')
    elif n == 127:
        n = int.from_bytes(rx(8), 'big')
    return rx(n).decode('utf-8')

_msg_id = 0
def call(sock, expr, timeout=20):
    global _msg_id
    _msg_id += 1
    mid = _msg_id
    send_frame(sock, json.dumps({
        'id': mid,
        'method': 'Runtime.evaluate',
        'params': {'expression': expr, 'returnByValue': True}
    }))
    sock.settimeout(timeout)
    while True:
        raw = recv_frame(sock)
        obj = json.loads(raw)
        if obj.get('id') == mid:
            res = obj.get('result', {}).get('result', {})
            return res.get('value', res.get('description', ''))

# 获取 page_id
resp = urllib.request.urlopen(f'http://{HOST}:{PORT}/json').read()
pages = json.loads(resp)
page_id = pages[0].get('id', '')
print(f"[PAGE_ID] {page_id}")

sock = ws_connect(page_id)
print("[OK] WebSocket 已连接\n")

# 点击"选择封面"按钮
print("[Step 1] 点击'选择封面'按钮...")
r = call(sock, """
(function(){
    var all = document.querySelectorAll('*');
    for (var el of all) {
        var t = (el.innerText || '').trim();
        if (t === '选择封面') {
            var rect = el.getBoundingClientRect();
            return JSON.stringify({
                x: Math.round(rect.left + rect.width / 2),
                y: Math.round(rect.top + rect.height / 2),
                text: t,
                found: true
            });
        }
    }
    return JSON.stringify({found: false});
})()
""")
print(f"  查找结果: {r[:100] if r else 'empty'}")

if r and 'found' in r:
    try:
        info = json.loads(r)
        if info.get('found'):
            x, y = info['x'], info['y']
            print(f"  点击 ({x}, {y})...")
            _msg_id += 1
            send_frame(sock, json.dumps({
                'id': _msg_id,
                'method': 'Input.dispatchMouseEvent',
                'params': {'type': 'mousePressed', 'x': x, 'y': y, 'button': 'left', 'clickCount': 1}
            }))
            recv_frame(sock)
            _msg_id += 1
            send_frame(sock, json.dumps({
                'id': _msg_id,
                'method': 'Input.dispatchMouseEvent',
                'params': {'type': 'mouseReleased', 'x': x, 'y': y, 'button': 'left', 'clickCount': 1}
            }))
            recv_frame(sock)
            print(f"  ✅ 已点击'选择封面'\n")
    except Exception as e:
        print(f"  ❌ 点击失败: {e}\n")
else:
    print("  ❌ 未找到'选择封面'按钮\n")

# 等待弹窗打开
print("[INFO] 等待弹窗打开...")
time.sleep(2)

sock.close()
print("[DONE]")
