# -*- coding: utf-8 -*-
"""强制刷新页面"""
import sys, socket, json, time
sys.stdout.reconfigure(encoding='utf-8')
HOST = "localhost"; PORT = 28800
PAGE_ID = "05A421A861953C0FFB3712503B85EE82"

def 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 send(s, d):
    d = d.encode('utf-8'); n = len(d); 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
    s.send(h + bytes(d[i]^m[i%4] for i in range(n)))

def recv(s):
    def rx(n):
        b = b''
        while len(b) < n: b += s.recv(n-len(b))
        return b
    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')

_mid = 0
def cdp(s, js, timeout=15):
    global _mid
    _mid += 1
    send(s, json.dumps({'id':_mid,'method':'Runtime.evaluate','params':{'expression':js,'returnByValue':True}}))
    s.settimeout(timeout)
    for _ in range(200):
        try:
            r = json.loads(recv(s))
            if r.get('id') == _mid:
                return r.get('result',{}).get('result',{}).get('value','')
        except: pass
    return ''

s = ws()
print("[OK] Connected")

# 强制刷新（Ctrl+Shift+R）
import json as j
_mid += 1
send(s, j.dumps({'id':_mid,'method':'Input.dispatchKeyEvent','params':{'type':'keyDown','key':'F5'}}))
recv(s)
_mid += 1
send(s, j.dumps({'id':_mid,'method':'Input.dispatchKeyEvent','params':{'type':'keyUp','key':'F5'}}))
recv(s)
print("[刷新] 已发送 F5")
time.sleep(3)

# 通过 CDP 导航到空白页
_mid += 1
send(s, json.dumps({'id':_mid,'method':'Page.navigate','params':{'url':'about:blank'}}))
recv(s)
time.sleep(1)

# 再导航到编辑页
_mid += 1
send(s, json.dumps({'id':_mid,'method':'Page.navigate','params':{'url':'https://baijiahao.baidu.com/builder/rc/edit?type=news'}}))
recv(s)
print("[导航] 等待页面加载...")
time.sleep(5)

# 检查当前 URL
r = cdp(s, "window.location.href")
print("[URL]", r)

# 检查字数
r = cdp(s, "var out=[];var els=document.querySelectorAll('*');for(var el of els){var t=(el.innerText||'').trim();if(t.match(/字数/)&&t.match(/\\d+/))out.push(t)}out.join(' | ')")
print("[字数]", r[:200] if r else 'empty')

# 检查 iframe UE 实例
r = cdp(s, "var ifr=document.querySelectorAll('iframe');var out=[];for(var i of ifr){try{var w=i.contentWindow;if(w.UE_V2&&w.UE_V2.instants){var ks=Object.keys(w.UE_V2.instants);for(var k of ks){var inst=w.UE_V2.instants[k];if(inst)out.push({key:inst.key||k,type:typeof inst.setContent})}}}catch(e){}}JSON.stringify(out)")
print("[UE]", r)

s.close()
