# -*- coding: utf-8 -*-
"""
手动设置封面图片
"""
import json
import time
import websocket
import urllib.request
import sys

sys.stdout.reconfigure(encoding='utf-8')

# 获取页面信息
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']

pages = get_pages()
page = pages[0]
page_id = page['id']

print(f"[OK] 连接到页面: {page_id}")

# 连接 WebSocket
ws = websocket.WebSocket()
ws.connect(page['webSocketDebuggerUrl'])

# 导航到草稿箱
print("[INFO] 导航到草稿箱...")
ws.send(json.dumps({
    'id': 1, 
    'method': 'Page.navigate', 
    'params': {'url': 'https://mp.weixin.qq.com/cgi-bin/draft?action=list&type=10&token=1808466501&lang=zh_CN'}
}))
time.sleep(3)

# 获取草稿列表
ws.send(json.dumps({
    'id': 2, 
    'method': 'Runtime.evaluate', 
    'params': {'expression': '''document.querySelectorAll(".appmsg_item").length'''}
}))
result = ws.recv()
print(f"[INFO] 草稿数量: {result}")

# 点击第一篇草稿
ws.send(json.dumps({
    'id': 3, 
    'method': 'Runtime.evaluate', 
    'params': {'expression': '''document.querySelector(".appmsg_item").click()'''}
}))
print("[INFO] 点击草稿")
time.sleep(3)

# 获取当前 URL
ws.send(json.dumps({'id': 4, 'method': 'Runtime.evaluate', 'params': {'expression': 'location.href'}}))
result = ws.recv()
print(f"[INFO] 当前URL: {result}")

ws.close()
print("[DONE]")
