# -*- coding: utf-8 -*-
"""
百家号深度诊断脚本
"""
import sys, socket, json, time, urllib.request, os

HOST = "localhost"
PORT = 9223

def get_bjh_page_id():
    pages = json.loads(urllib.request.urlopen(f'http://{HOST}:{PORT}/json').read())
    for p in pages:
        url = p.get('url', '')
        if 'baijiahao.baidu.com' in url and ('edit' in url or 'builder' in url):
            return p['id']
    return None

def ws_connect(page_id):
    import urllib.parse
    ws_url = f"ws://{HOST}:{PORT}/devtools/page/{page_id}"
    parsed = urllib.parse.urlparse(ws_url)
    sock = socket.create_connection((parsed.hostname, parsed.port or 80), timeout=15)
    key = 'dGhlIHNhbXBsZSBub25jZQ=='
    handshake = (
        f'GET {parsed.path} HTTP/1.1\r\n'
        f'Host: {parsed.hostname}:{parsed.port}\r\n'
        'Upgrade: websocket\r\nConnection: Upgrade\r\n'
        f'Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n'
    )
    sock.send(handshake.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')

_msg_id = 0
def call(sock, expr, timeout=15):
    global _msg_id
    _msg_id += 1
    mid = _msg_id
    send_frame(sock, json.dumps({
        'id': mid,
        'method': 'Runtime.evaluate',
        'params': {'expression': expr, 'returnByValue': True}
    }))
    sock.settimeout(timeout)
    while True:
        raw = recv_frame(sock)
        obj = json.loads(raw)
        if obj.get('id') == mid:
            res = obj.get('result', {}).get('result', {})
            return res.get('value', res.get('description', ''))

# 主程序
page_id = get_bjh_page_id()
if not page_id:
    print("[ERROR] 未找到百家号编辑页面")
    sys.exit(1)
print(f"[OK] Page ID: {page_id}")

sock = ws_connect(page_id)
print("[OK] WebSocket 已连接")

# 深度诊断
print("\n" + "="*60)
print("深度诊断 - 寻找所有可能的输入元素")
print("="*60)

# 1. 查找所有 input
r = call(sock, """
(function(){
    var results = [];
    var inputs = document.querySelectorAll('input');
    for(var i=0; i<inputs.length; i++){
        var inp = inputs[i];
        results.push({
            tag: inp.tagName,
            type: inp.type,
            placeholder: inp.placeholder || '',
            className: inp.className || '',
            id: inp.id || '',
            maxLength: inp.maxLength || '',
            value: inp.value ? inp.value.substring(0,20) : ''
        });
    }
    return JSON.stringify(results);
})()
""")
print("\n[所有 input 元素]:")
try:
    inputs = json.loads(r)
    for inp in inputs[:20]:  # 只显示前20个
        print(f"  {inp}")
except:
    print(f"  解析失败: {r[:200]}")

# 2. 查找所有 contenteditable
r = call(sock, """
(function(){
    var results = [];
    var els = document.querySelectorAll('[contenteditable]');
    for(var i=0; i<els.length; i++){
        var el = els[i];
        results.push({
            tag: el.tagName,
            className: el.className ? el.className.substring(0,50) : '',
            id: el.id || '',
            contenteditable: el.contenteditable,
            innerText: el.innerText ? el.innerText.substring(0,30) : ''
        });
    }
    return JSON.stringify(results);
})()
""")
print("\n[所有 contenteditable 元素]:")
try:
    els = json.loads(r)
    for el in els[:10]:
        print(f"  {el}")
except:
    print(f"  解析失败: {r[:200]}")

# 3. 查找 cheetah-input 组件
r = call(sock, """
(function(){
    var results = [];
    var els = document.querySelectorAll('cheetah-input');
    for(var i=0; i<els.length; i++){
        var el = els[i];
        var input = el.querySelector('input');
        results.push({
            tag: 'cheetah-input',
            className: el.className || '',
            hasInput: !!input,
            inputValue: input ? (input.value || '').substring(0,30) : '',
            inputPlaceholder: input ? (input.placeholder || '') : ''
        });
    }
    return JSON.stringify(results);
})()
""")
print("\n[cheetah-input 组件]:")
try:
    els = json.loads(r)
    for el in els:
        print(f"  {el}")
except:
    print(f"  解析失败: {r[:200]}")

# 4. 尝试直接获取页面中的可见文本
r = call(sock, """
(function(){
    var body = document.body;
    return body.innerText.substring(0, 500);
})()
""")
print("\n[页面可见文本片段]:")
print(r[:500])

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