# -*- coding: utf-8 -*-
"""
插入图片到公众号文章
"""
import sys, socket, json, base64, urllib.request, time, os, struct
sys.stdout.reconfigure(encoding='utf-8', errors='replace')

HOST = 'localhost'
PORT = 9222

def get_first_page():
    pages = json.loads(urllib.request.urlopen(f'http://{HOST}:{PORT}/json', timeout=5).read())
    for p in pages:
        if p.get('type') == 'page':
            return p
    return None

def ws_connect(url):
    import urllib.parse
    parsed = urllib.parse.urlparse(url)
    sock = socket.create_connection((parsed.hostname, parsed.port or 80), timeout=10)
    key = 'dGhlIHNhbXBsZSBub25jZQ=='
    hs = f'GET {parsed.path} HTTP/1.1\r\nHost: {parsed.hostname}:{parsed.port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n'
    sock.send(hs.encode())
    resp = b''
    while b'\r\n\r\n' not in resp:
        resp += sock.recv(4096)
    return sock

def send_frame(sock, data):
    data = data.encode('utf-8')
    n = len(data)
    mask = b'\x01\x02\x03\x04'
    if n <= 125:
        hdr = bytes([0x81, n | 0x80]) + mask
    elif n <= 65535:
        hdr = bytes([0x81, 0xFE]) + n.to_bytes(2, 'big') + mask
    else:
        hdr = bytes([0x81, 0xFF]) + n.to_bytes(8, 'big') + mask
    sock.send(hdr + bytes(data[i] ^ mask[i % 4] for i in range(n)))

def recv_frame(sock):
    def rx(n):
        buf = b''
        while len(buf) < n:
            buf += sock.recv(n - len(buf))
        return buf
    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_call(sock, method, params=None):
    global _mid
    _mid += 1
    msg = {'id': _mid, 'method': method}
    if params:
        msg['params'] = params
    send_frame(sock, json.dumps(msg))
    sock.settimeout(60)
    while True:
        raw = recv_frame(sock)
        obj = json.loads(raw)
        if obj.get('id') == _mid:
            return obj.get('result', {})

page = get_first_page()
sock = ws_connect(page['webSocketDebuggerUrl'])

# 图片路径
img_path = r'D:\wxpic\Screenshot_20260319_071251_com_hihonor_photos_GalleryMain.jpg'

# 读取图片
print('读取图片...')
with open(img_path, 'rb') as f:
    img_data = base64.b64encode(f.read()).decode('utf-8')
print(f'图片大小: {len(img_data)} bytes')

# 方法：点击图片上传按钮，然后模拟文件选择
# 先点击工具栏的图片按钮
print('点击图片上传按钮...')

# 查找图片按钮
result = cdp_call(sock, 'Runtime.evaluate', {'expression': '''
(function(){
    // 查找工具栏中的图片按钮
    var btns = document.querySelectorAll("button, a");
    for(var b of btns) {
        var t = b.innerText || "";
        if(t.includes("图片") || t.includes("img") || t.includes("photo")) {
            var rect = b.getBoundingClientRect();
            if(rect.width > 0 && rect.height > 0) {
                return "found: " + b.innerText.substring(0,20);
            }
        }
    }
    return "not found";
})()
'''})
print('按钮查找:', result)

# 尝试用剪贴板方式插入图片
# 先把光标移动到文章末尾
result = cdp_call(sock, 'Runtime.evaluate', {'expression': '''
var editor = document.querySelector(".ProseMirror");
if(editor) {
    // 添加图片元素
    var imgContainer = document.createElement("div");
    imgContainer.style.margin = "10px 0";
    imgContainer.style.textAlign = "center";
    
    var img = document.createElement("img");
    img.src = "data:image/jpeg;base64,' + img_data + '";
    img.style.maxWidth = "100%";
    img.style.height = "auto";
    
    imgContainer.appendChild(img);
    editor.appendChild(imgContainer);
    "OK: 图片已插入";
} else {
    "FAIL: 编辑器未找到";
}
'''})
print('插入图片:', result)

sock.close()
print('完成')
