# -*- coding: utf-8 -*-
"""清标题 + 存草稿"""
import sys, socket, json, time
sys.stdout.reconfigure(encoding='utf-8')
HOST = "localhost"; PORT = 28800
PAGE_ID = "70039F329097C14448996F189E3A42A1"

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=20):
    global _mid
    _mid += 1
    send(s, json.dumps({'id':_mid,'method':'Runtime.evaluate','params':{'expression':js,'returnByValue':True}}))
    s.settimeout(timeout)
    for _ in range(300):
        try:
            r = json.loads(recv(s))
            if r.get('id') == _mid:
                return r.get('result',{}).get('result',{}).get('value','')
        except: pass
    return ''

def mouse_click(s, x, y, n=1):
    global _mid
    for t in ['mousePressed','mouseReleased']:
        _mid += 1
        send(s, json.dumps({'id':_mid,'method':'Input.dispatchMouseEvent','params':{'type':t,'x':x,'y':y,'button':'left','clickCount':n}}))
        recv(s)
        time.sleep(0.05)

def key(s, k, txt=''):
    global _mid
    for t in ['keyDown','keyUp']:
        _mid += 1
        p = {'type':t,'key':k}
        if txt: p['text'] = txt
        send(s, json.dumps({'id':_mid,'method':'Input.dispatchKeyEvent','params':p}))
        recv(s)
    time.sleep(0.03)

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

# Step 1: 滚到顶部
print("[Step 1] 滚到顶部...")
cdp(s, "window.scrollTo(0, 0)")
time.sleep(0.5)

# Step 2: 找标题段落位置
print("[Step 2] 找标题...")
r = cdp(s, "var ps=document.querySelectorAll('p');var out=[];for(var p of ps){var t=(p.innerText||'').trim();if(t.length>0&&t.length<300&&!t.includes('插入')&&!t.includes('AI助手')&&!t.includes('热点')&&!t.includes('灵感')){var rect=p.getBoundingClientRect();out.push({x:Math.round(rect.left+rect.width/2),y:Math.round(rect.top+rect.height/2),text:t.substring(0,30)})}}JSON.stringify(out)")
print("  位置:", r[:100] if r else 'empty')
if r and 'x' in r:
    info = json.loads(r)
    if info:
        x, y = info[0]['x'], info[0]['y']
        print("  点击 (%d, %d)..." % (x, y))
        # Triple-click
        for n in [1, 2, 3]:
            for evt in ['mousePressed','mouseReleased']:
                _mid += 1
                send(s, json.dumps({'id':_mid,'method':'Input.dispatchMouseEvent','params':{'type':evt,'x':x,'y':y,'button':'left','clickCount':n}}))
                recv(s)
                time.sleep(0.08)
        time.sleep(0.3)
        key(s, 'Delete')
        time.sleep(0.2)
        # 输入新标题
        title = '水稻"长寿基因"刷屏背后：农业科技崛起，这类专业成升学就业新风口'
        print("  输入:", title[:20], "...")
        for ch in title:
            key(s, ch, ch)
        time.sleep(0.3)
        r2 = cdp(s, "var ps=document.querySelectorAll('p');var f='';for(var p of ps){var t=(p.innerText||'').trim();if(t.indexOf('长寿基因')>-1)f=t.substring(0,40)}f")
        print("  标题:", r2)

# Step 3: 点存草稿
print("\n[Step 3] 点存草稿...")
r = cdp(s, "var els=document.querySelectorAll('*');var out=[];for(var el of els){var t=(el.innerText||'').trim();if(t==='存草稿'){var rect=el.getBoundingClientRect();if(rect.width>0&&rect.height>0)out.push({x:Math.round(rect.left+rect.width/2),y:Math.round(rect.top+rect.height/2)})}}JSON.stringify(out)")
print("  按钮:", r[:80] if r else 'not found')
if r and 'x' in r:
    info = json.loads(r)
    if info:
        x, y = info[0]['x'], info[0]['y']
        print("  点击 (%d, %d)..." % (x, y))
        mouse_click(s, x, y)
        time.sleep(2)
        r2 = cdp(s, "var els=document.querySelectorAll('*');var f='';for(var el of els){var t=(el.innerText||'').trim();if(t.includes('已保存'))f=t}if(!f){var els2=document.querySelectorAll('*');for(var el of els2){var t2=(el.innerText||'').trim();if(t2.match(/字数/)&&t2.match(/\\d+/))f=t2}}f")
        print("  状态:", r2[:80] if r2 else 'empty')

print("\n✅ 完成")
s.close()
