# -*- coding: utf-8 -*-
"""诊断：检查文首图片是否注入成功"""
import sys, socket, json, time
import urllib.request

HOST = "127.0.0.1"
PORT = 9222

# 获取页面 ID
pages = json.loads(urllib.request.urlopen(f'http://{HOST}:{PORT}/json', timeout=5).read())
page = None
for p in pages:
    if 'baijiahao' in p.get('url', '') and 'edit' in p.get('url', ''):
        page = p
        break

if not page:
    print("[ERROR] 未找到百家号编辑器页面")
    sys.exit(1)

PAGE_ID = page['id']
print(f"[OK] Page ID: {PAGE_ID[:20]}...")

def ws(page_id):
    import urllib.parse
    u = f"ws://{HOST}:{PORT}/devtools/page/{page_id}"
    p = urllib.parse.urlparse(u)
    s = socket.create_connection((p.hostname, p.port or 80), timeout=15)
    req = (f"GET {p.path} HTTP/1.1\r\n"
           f"Host: {p.hostname}:{p.port}\r\n"
           f"Upgrade: websocket\r\n"
           f"Connection: Upgrade\r\n"
           f"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
           f"Sec-WebSocket-Version: 13\r\n\r\n")
    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 call(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 ''

sock = ws(PAGE_ID)
print("[OK] 已连接\n")

# 检查正文 iframe 中是否有 img 标签
print("[检查] 正文中的 img 标签...")
r = call(sock, """
(function() {
    var ifr = document.querySelector('iframe');
    if (!ifr) return 'no_iframe';
    var doc = ifr.contentDocument || ifr.contentWindow.document;
    if (!doc) return 'no_doc';
    var imgs = doc.querySelectorAll('img');
    if (imgs.length === 0) return 'no_images';
    var result = [];
    for (var img of imgs) {
        result.push({
            src_prefix: (img.src || '').substring(0, 80),
            style: (img.style.cssText || '').substring(0, 100)
        });
    }
    return JSON.stringify(result);
})()
""")
print(f"  正文 img: {r[:500] if r else 'empty'}\n")

# 检查封面区域
print("[检查] 封面区域...")
r = call(sock, """
(function() {
    // 找所有包含"封面"文字的元素
    var all = document.querySelectorAll('*');
    var coverInfo = [];
    for (var el of all) {
        var t = (el.innerText || '').trim();
        if (t.includes('封面')) {
            var parent = el.parentElement;
            while (parent && parent.children.length < 2) {
                parent = parent.parentElement;
            }
            if (parent) {
                var imgs = parent.querySelectorAll('img');
                var imgInfo = [];
                for (var img of imgs) {
                    imgInfo.push({
                        src_prefix: (img.src || '').substring(0, 50),
                        w: img.naturalWidth || img.width,
                        h: img.naturalHeight || img.height
                    });
                }
                coverInfo.push({
                    text: t,
                    parent_tag: parent.tagName,
                    img_count: imgs.length,
                    imgs: imgInfo
                });
            }
        }
    }
    return JSON.stringify(coverInfo);
})()
""")
print(f"  封面: {r[:600] if r else 'empty'}\n")

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