# -*- coding: utf-8 -*-
"""上传封面图（注入到图片 input，跳过视频）"""
import sys, socket, json, time, base64, os, glob
from base64 import b64encode
sys.stdout.reconfigure(encoding='utf-8')
HOST = "localhost"; PORT = 28800
PAGE_ID = "70039F329097C14448996F189E3A42A1"

IMG_LIST = glob.glob(r'D:\wxpic\*.jpg') + glob.glob(r'D:\wxpic\*.png')
IMG_PATH = max(IMG_LIST, key=os.path.getmtime) if IMG_LIST else None
with open(IMG_PATH, 'rb') as f:
    IMG_B64 = b64encode(f.read()).decode()
ext = os.path.splitext(IMG_PATH)[1].lower()
IMG_MIME = 'image/jpeg' if ext in ['.jpg','.jpeg'] else 'image/png'
print("[INFO] 图片:", IMG_PATH, "size:", len(IMG_B64))

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")

# 注入 base64
cdp(s, "window.__COVER_B64__='%s'" % IMG_B64, timeout=5)
cdp(s, "window.__COVER_MIME__='%s'" % IMG_MIME, timeout=5)

# 只对 index 1（图片 input）注入，跳过 index 0（视频）
print("[Step 1] 注入图片到封面 input...")
r = cdp(s, """
(function() {
  var inputs = document.querySelectorAll('input[type=file]');
  var result = [];
  for (var i = 0; i < inputs.length; i++) {
    var inp = inputs[i];
    var accept = (inp.accept || '').toLowerCase();
    // 跳过视频
    if (accept.indexOf('video') > -1) {
      result.push({index: i, type: 'VIDEO', skipped: true});
      continue;
    }
    // 图片上传
    try {
      var b64 = window.__COVER_B64__ || '';
      var mime = window.__COVER_MIME__ || 'image/jpeg';
      var byteString = atob(b64);
      var ab = new ArrayBuffer(byteString.length);
      var ia = new Uint8Array(ab);
      for (var j = 0; j < byteString.length; j++) ia[j] = byteString.charCodeAt(j);
      var blob = new Blob([ab], {type: mime});
      var file = new File([blob], 'cover.jpg', {type: mime});
      // 构造 DataTransfer 并覆盖 files
      var dt = new DataTransfer();
      dt.items.add(file);
      Object.defineProperty(inp, 'files', {
        value: dt.files,
        writable: true,
        configurable: true
      });
      // 触发 change 事件
      inp.dispatchEvent(new Event('change', {bubbles: true}));
      result.push({index: i, type: 'IMAGE', ok: true, name: file.name, size: file.size});
    } catch(e) {
      result.push({index: i, type: 'IMAGE', ok: false, err: e.message});
    }
  }
  return JSON.stringify(result);
})()
""", timeout=20)
print("  注入结果:", r[:300] if r else 'empty')

print("\n[等待] 封面上传中（10秒）...")
time.sleep(10)

# 检查封面图
print("\n[Step 2] 检查封面...")
r = cdp(s, """
(function() {
  // 找封面区域的 img（通常宽>高，是横向图片）
  var imgs = document.querySelectorAll('img');
  var result = [];
  for (var img of imgs) {
    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({w: w, h: h, isData: src.indexOf('data:') > -1, src: src.substring(0, 40)});
    }
  }
  // 也检查封面区域附近
  var all = document.querySelectorAll('*');
  var coverInfo = [];
  for (var el of all) {
    var t = (el.innerText || '').trim();
    if (t.includes('上传成功') || t.includes('已上传')) {
      coverInfo.push(t);
    }
  }
  return JSON.stringify({imgs: result.slice(0,5), cover_status: coverInfo});
})()
""")
print("  封面检查:", r[:400] if r else 'empty')

# 检查页面是否还有错误提示
r = cdp(s, """
(function() {
  var all = document.querySelectorAll('*');
  var errors = [];
  for (var el of all) {
    var t = (el.innerText || '').trim();
    if (t.includes('格式不正确') || t.includes('上传失败') || t.includes('error')) {
      errors.push(t.substring(0, 50));
    }
  }
  return errors.join(' | ') || 'no_error';
})()
""")
print("  错误检查:", r[:200] if r else 'empty')

print("\n✅ 完成，请查看浏览器确认封面")
s.close()
