# -*- coding: utf-8 -*-
"""检查封面状态"""
import sys, socket, json, time
sys.stdout.reconfigure(encoding='utf-8')
HOST = "localhost"; PORT = 28800
PAGE_ID = "70039F329097C14448996F189E3A42A1"

def ws():
    import urllib.parse
    u = "ws://%s:%s/devtools/page/%s" % (HOST, PORT, PAGE_ID)
    p = urllib.parse.urlparse(u)
    s = socket.create_connection((p.hostname, p.port or 80), timeout=15)
    req = ("GET %s HTTP/1.1\r\nHost: %s:%s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n" % (p.path, p.hostname, p.port))
    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 cdp(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 ''

s = ws()
print("[OK] Connected\n")

# 等3秒后再检查
import time as t
t.sleep(3)

# 检查封面区域 img
r = cdp(s, """
(function() {
  var allImgs = document.querySelectorAll('img');
  var result = [];
  for (var img of allImgs) {
    var w = img.naturalWidth || img.width || 0;
    var h = img.naturalHeight || img.height || 0;
    var src = img.src || '';
    if (w > 50 && h > 50 && src.indexOf('vcg') === -1 && src.indexOf('copyright') === -1) {
      result.push({
        src: src.substring(0, 60),
        w: w,
        h: h,
        isData: src.indexOf('data:image') > -1
      });
    }
  }
  return JSON.stringify(result);
})()
""")
print("封面图检查:", r[:400] if r else 'empty')

# 看看页面里有没有"上传成功"或"处理中"
r = cdp(s, """
(function() {
  var all = document.querySelectorAll('*');
  var out = [];
  for (var el of all) {
    var t = (el.innerText || '').trim();
    if (t.includes('上传') || t.includes('处理中') || t.includes('loading') || t.includes('Loading')) {
      out.push(t.substring(0, 40));
    }
  }
  return out.slice(0, 5).join(' | ') || 'none';
})()
""")
print("上传状态:", r[:200] if r else 'empty')

# 检查封面组件里的 img URL
r = cdp(s, """
(function() {
  // 找封面区域的 img（宽度>高度 or 有特点的）
  var imgs = document.querySelectorAll('img');
  var result = [];
  for (var img of imgs) {
    var w = img.naturalWidth || img.width;
    var h = img.naturalHeight || img.height;
    var src = img.src || '';
    if (w > 80 && h > 80) {
      result.push({w: w, h: h, src_prefix: src.substring(0, 60), isData: src.indexOf('data:') > -1, id: img.id, class: img.className.substring(0,20)});
    }
  }
  return JSON.stringify(result);
})()
""")
print("所有大图:", r[:500] if r else 'empty')
s.close()
