#!/usr/bin/env python3
"""修复标题 - 使用 CDP Input"""
import socket, json, urllib.request, urllib.parse, time

HOST = 'localhost'
PORT = 9223
pages = json.loads(urllib.request.urlopen(f'http://{HOST}:{PORT}/json').read())
page_id = [p['id'] for p in pages if 'baijiahao.baidu.com' in p['url']][0]

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\nHost:{parsed.hostname}:{parsed.port}\r\nUpgrade:websocket\r\nConnection:Upgrade\r\nSec-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)

def send(s, d):
    data = json.dumps(d).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
    s.send(hdr + bytes(data[i] ^ mask[i%4] for i in range(n)))

def recv(s):
    h = s.recv(2)
    n = h[1] & 0x7f
    if n == 126:
        n = int.from_bytes(s.recv(2), 'big')
    elif n == 127:
        n = int.from_bytes(s.recv(8), 'big')
    return s.recv(n).decode('utf-8')

print("Step 1: 找到并点击标题框")

# 先找到标题元素
find_expr = '''
(function(){
    var box = document.querySelector('.input-box');
    if(box){
        var rect = box.getBoundingClientRect();
        return JSON.stringify({found: true, top: rect.top, left: rect.left, text: box.innerText.substring(0,30)});
    }
    return JSON.stringify({found: false});
})()
'''
send(sock, {'id':1,'method':'Runtime.evaluate','params':{'expression':find_expr}})
r = recv(sock)
result = json.loads(r)['result']['result']['value']
print("  标题框:", result)

print("\nStep 2: 使用 CDP Input.dispatchKeyEvents 模拟输入")
# 使用 CDP Input 输入标题
title = "山东第二医科大学：山东省重点大学还是普通本科？"
# 先点击标题框
send(sock, {'id':2,'method':'Input.dispatchMouseEvent','params':{'type':'mousePressed','x':300,'y':120}})
recv(sock)
send(sock, {'id':3,'method':'Input.dispatchMouseEvent','params':{'type':'mouseReleased','x':300,'y':120}})
print("  已点击标题框")

time.sleep(0.5)

# 发送键盘事件输入标题
for char in title:
    send(sock, {'id':4,'method':'Input.dispatchKeyEvent','params':{'type':'keyDown','text':char}})
    recv(sock)
    send(sock, {'id':5,'method':'Input.dispatchKeyEvent','params':{'type':'keyUp','text':char}})
    recv(sock)

print(f"  已输入标题: {title}")

# 验证
verify_expr = '''
(function(){
    var box = document.querySelector('.input-box');
    return box ? box.innerText : 'no box';
})()
'''
send(sock, {'id':6,'method':'Runtime.evaluate','params':{'expression':verify_expr}})
r = recv(sock)
result = json.loads(r)['result']['result']['value']
print("  当前标题:", result)

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