import sys
sys.stdout.reconfigure(encoding='utf-8')
import socket, base64, json, time, urllib.request

def get_pages():
    data = json.loads(urllib.request.urlopen('http://localhost:9222/json', timeout=3).read())
    return [t for t in data if t.get('type') == 'page']

def ws_handshake(s, host, path):
    key = base64.b64encode(b'workbuddy12345678').decode()
    req = (
        f"GET {path} HTTP/1.1\r\n"
        f"Host: {host}\r\n"
        "Upgrade: websocket\r\n"
        "Connection: Upgrade\r\n"
        f"Sec-WebSocket-Key: {key}\r\n"
        "Sec-WebSocket-Version: 13\r\n\r\n"
    )
    s.sendall(req.encode())
    resp = b''
    while b'\r\n\r\n' not in resp:
        resp += s.recv(4096)

def ws_send(s, obj):
    data = json.dumps(obj).encode('utf-8')
    length = len(data)
    mask_key = b'\x00\x00\x00\x00'
    if length < 126:
        header = bytes([0x81, 0x80 | length])
    elif length < 65536:
        header = bytes([0x81, 0xFE, length >> 8, length & 0xFF])
    else:
        header = bytes([0x81, 0xFF] + [(length >> (8*i)) & 0xFF for i in range(7, -1, -1)])
    s.sendall(header + mask_key + data)

def ws_recv(s):
    def recv_exact(n):
        buf = b''
        while len(buf) < n:
            chunk = s.recv(n - len(buf))
            if not chunk:
                raise ConnectionError('connection closed')
            buf += chunk
        return buf
    b0, b1 = recv_exact(2)
    masked = (b1 & 0x80) != 0
    length = b1 & 0x7F
    if length == 126:
        length = int.from_bytes(recv_exact(2), 'big')
    elif length == 127:
        length = int.from_bytes(recv_exact(8), 'big')
    mask = recv_exact(4) if masked else b'\x00\x00\x00\x00'
    payload = bytearray(recv_exact(length))
    if masked:
        for i in range(length):
            payload[i] ^= mask[i % 4]
    return json.loads(payload.decode('utf-8'))

def cdp_call(s, mid, method, params=None):
    msg = {"id": mid, "method": method}
    if params:
        msg["params"] = params
    ws_send(s, msg)
    while True:
        r = ws_recv(s)
        if r.get('id') == mid:
            return r

# 获取当前页面
pages = get_pages()
page = pages[0]
page_id = page['id']
token = ''

# 从URL里提取token
import re
m = re.search(r'token=(\d+)', page['url'])
if m:
    token = m.group(1)
    print(f'[OK] Token: {token}')
else:
    print('[WARN] Token not found in URL, will try without')

s = socket.socket()
s.settimeout(15)
s.connect(('127.0.0.1', 9222))
ws_handshake(s, '127.0.0.1', f'/devtools/page/{page_id}')
print('[OK] Connected')

# 直接导航到新建图文页面
new_article_url = f'https://mp.weixin.qq.com/cgi-bin/appmsg?action=edit&type=10&token={token}&lang=zh_CN'
r = cdp_call(s, 1, 'Page.navigate', {'url': new_article_url})
print(f'[OK] Navigating to new article editor...')

# 等待页面加载
time.sleep(3)

# 检查当前URL
pages2 = get_pages()
for p in pages2:
    if p.get('type') == 'page':
        print(f'[OK] Current URL: {p["url"][:100]}')

s.close()
print('[DONE]')
