# -*- coding: utf-8 -*-
"""诊断：检查 UEditor 和页面状态"""
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 数量和 UEditor
print("[检查] iframe 和 UEditor...")
r = call(sock, """
(function() {
    var ifrs = document.querySelectorAll('iframe');
    var ifrInfo = [];
    for (var i = 0; i < ifrs.length; i++) {
        var ifr = ifrs[i];
        var rect = ifr.getBoundingClientRect();
        var hasUE = false;
        var ueReady = false;
        try {
            var w = ifr.contentWindow || ifr.contentDocument.defaultView;
            if (w.UE_V2 && w.UE_V2.instants) {
                hasUE = true;
                var insts = Object.keys(w.UE_V2.instants);
                for (var k of insts) {
                    var inst = w.UE_V2.instants[k];
                    if (inst && inst.key && inst.key.indexOf('content') > -1) {
                        ueReady = true;
                    }
                }
            }
        } catch(e) {
            // iframe 可能还没加载
        }
        ifrInfo.push({
            index: i,
            visible: rect.width > 0 && rect.height > 0,
            hasUE: hasUE,
            ueReady: ueReady
        });
    }
    return JSON.stringify(ifrInfo);
})()
""")
print(f"  iframe 状态: {r[:500] if r else 'empty'}\n")

# 检查是否还有其他编辑器（非 iframe）
print("[检查] 主文档中的编辑器...")
r = call(sock, """
(function() {
    var hasUE = false;
    var hasContent = false;
    
    // 检查主文档的 UE
    if (window.UE_V2 && window.UE_V2.instants) {
        hasUE = true;
        var insts = Object.keys(window.UE_V2.instants);
        for (var k of insts) {
            var inst = window.UE_V2.instants[k];
            if (inst && inst.key && inst.key.indexOf('content') > -1) {
                hasContent = true;
            }
        }
    }
    
    // 检查所有 contenteditable
    var ce = document.querySelectorAll('[contenteditable]');
    var ceInfo = [];
    for (var i = 0; i < ce.length; i++) {
        var el = ce[i];
        var rect = el.getBoundingClientRect();
        var t = (el.innerText || '').trim();
        ceInfo.push({
            index: i,
            visible: rect.width > 0 && rect.height > 0,
            text_len: t.length,
            text_preview: t.substring(0, 30)
        });
    }
    
    return JSON.stringify({
        hasUE: hasUE,
        hasContent: hasContent,
        contenteditables: ceInfo.slice(0, 5)
    });
})()
""")
print(f"  主文档编辑器: {r[:500] if r else 'empty'}\n")

# 检查页面是否完全加载
print("[检查] 页面加载状态...")
r = call(sock, """
(function() {
    return {
        readyState: document.readyState,
        url: window.location.href.substring(0, 100),
        title: document.title.substring(0, 50)
    };
})()
""")
print(f"  页面状态: {r}\n")

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