#!/usr/bin/env python3
"""简单修复标题"""
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 = 'ws://%s:%s/devtools/page/%s' % (HOST, PORT, page_id)
from urllib.parse import urlparse
parsed = urlparse(ws_url)
sock = socket.create_connection((parsed.hostname, parsed.port or 80), timeout=15)
key = 'dGhlIHNhbXBsZSBub25jZQ=='
handshake = 'GET %s HTTP/1.1\r\nHost:%s\r\nUpgrade:websocket\r\nConnection:Upgrade\r\nSec-WebSocket-Key:%s\r\nSec-WebSocket-Version:13\r\n\r\n' % (parsed.path, parsed.hostname, key)
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
    else:
        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')
    return s.recv(n).decode('utf-8')

# 标题
title = "山东第二医科大学：山东省重点大学还是普通本科？"

# Step 1: 点击标题框获得焦点
print("Step 1: 点击标题框")
expr1 = "document.querySelector('.input-box').focus()"
send(sock, {'id':1,'method':'Runtime.evaluate','params':{'expression':expr1}})
recv(sock)
print("  已聚焦")

time.sleep(0.5)

# Step 2: 使用 CDP Input 模拟打字
print("Step 2: 模拟输入标题")
for i, char in enumerate(title):
    send(sock, {'id':2,'method':'Input.dispatchKeyEvent','params':{'type':'keyDown','text':char}})
    recv(sock)
    send(sock, {'id':3,'method':'Input.dispatchKeyEvent','params':{'type':'keyUp','text':char}})
    recv(sock)
    if (i+1) % 10 == 0:
        print(f"  已输入 {i+1}/{len(title)} 字符")

print(f"  完成! 共输入 {len(title)} 字符")

# Step 3: 验证
print("Step 3: 验证")
expr3 = "document.querySelector('.input-box').innerText"
send(sock, {'id':4,'method':'Runtime.evaluate','params':{'expression':expr3}})
r = recv(sock)
result = json.loads(r)
val = result.get('result', {}).get('result', {}).get('value', 'error')
print(f"  当前标题: {val}")

sock.close()
print("\n完成! 请查看页面")
