# -*- coding: utf-8 -*-
"""点击选择封面按钮并上传"""
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"

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 ''

def mouse_click(s, x, y):
    global _mid
    for t in ['mousePressed','mouseReleased']:
        _mid += 1
        send(s, json.dumps({'id':_mid,'method':'Input.dispatchMouseEvent','params':{'type':t,'x':x,'y':y,'button':'left','clickCount':1}}))
        recv(s)
        time.sleep(0.05)

def key(s, k, txt=''):
    global _mid
    for t in ['keyDown','keyUp']:
        _mid += 1
        p = {'type':t,'key':k}
        if txt: p['text'] = txt
        send(s, json.dumps({'id':_mid,'method':'Input.dispatchKeyEvent','params':p}))
        recv(s)
    time.sleep(0.04)

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

# Step 1: 点击"选择封面"按钮 (442, 3203)
print("[Step 1] 点击选择封面按钮...")
mouse_click(s, 442, 3203)
time.sleep(1)

# 检查是否有文件对话框打开或者新的 DOM 元素出现
r = cdp(s, """
(function() {
  // 找所有 input[type=file] 及其可见性
  var inputs = document.querySelectorAll('input[type=file]');
  var result = [];
  for (var i = 0; i < inputs.length; i++) {
    var inp = inputs[i];
    var rect = inp.getBoundingClientRect();
    var s = window.getComputedStyle(inp);
    result.push({
      index: i,
      accept: inp.accept,
      display: s.display,
      visibility: s.visibility,
      width: Math.round(rect.width),
      height: Math.round(rect.height),
      parent: inp.parentElement ? inp.parentElement.tagName + '.' + inp.parentElement.className.substring(0,30) : ''
    });
  }
  return JSON.stringify(result);
})()
""")
print("  file inputs after click:", r[:200] if r else 'empty')

# Step 2: 找封面图相关的 label/div 是否出现
r = cdp(s, """
(function() {
  // 找封面区域的 img 标签
  var imgs = document.querySelectorAll('img');
  var result = [];
  for (var i = 0; i < imgs.length; i++) {
    var img = imgs[i];
    var rect = img.getBoundingClientRect();
    var s = window.getComputedStyle(img);
    result.push({
      index: i,
      src_prefix: (img.src || '').substring(0, 30),
      display: s.display,
      w: Math.round(rect.width),
      h: Math.round(rect.height),
      class: img.className.substring(0,30)
    });
  }
  return JSON.stringify(result);
})()
""")
print("  封面 img:", r[:200] if r else 'empty')

# Step 3: 尝试直接把 File 对象注入到 file input
# 先读图片
IMG_PATH = glob.glob(r'D:\wxpic\*.jpg')
if not IMG_PATH:
    IMG_PATH = glob.glob(r'D:\wxpic\*.png')
IMG_PATH = IMG_PATH[0] if IMG_PATH else None
print("\n  图片:", IMG_PATH)

if IMG_PATH:
    with open(IMG_PATH, 'rb') as f:
        img_b64 = b64encode(f.read()).decode()
    ext = os.path.splitext(IMG_PATH)[1].lower()
    mime = 'image/jpeg' if ext in ['.jpg','.jpeg'] else 'image/png'
    img_name = 'cover.jpg'

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

    # 方法：通过 file input 的 parent div 找隐藏的 input，然后注入
    r = cdp(s, """
(function() {
  var b64 = window.__COVER_B64__ || '';
  var mime = window.__COVER_MIME__ || 'image/jpeg';
  if (!b64) return 'no_b64';

  var byteString = atob(b64);
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);
  for (var i = 0; i < byteString.length; i++) ia[i] = byteString.charCodeAt(i);
  var blob = new Blob([ab], {type: mime});
  var file = new File([blob], 'cover.jpg', {type: mime});

  // 找所有 input
  var inputs = document.querySelectorAll('input');
  var result = 'no_input';
  for (var i = 0; i < inputs.length; i++) {
    var inp = inputs[i];
    // 尝试直接注入 files
    try {
      Object.defineProperty(inp, 'files', {
        value: [file],
        writable: true,
        configurable: true
      });
      var evt = new Event('change', {bubbles: true, cancelable: true});
      inp.dispatchEvent(evt);
      result = 'ok:' + inp.files.length + ' files, accept:' + inp.accept;
    } catch(e) {
      result = 'err:' + e.message.substring(0, 30);
    }
  }
  return result;
})()
""", timeout=20)
    print("  注入结果:", r[:100] if r else 'empty')
    time.sleep(2)

# 检查封面是否上传成功
r = cdp(s, """
(function() {
  // 找封面 img
  var imgs = document.querySelectorAll('img');
  var result = [];
  for (var i = 0; i < imgs.length; i++) {
    var img = imgs[i];
    var rect = img.getBoundingClientRect();
    if (rect.width > 50 && rect.height > 50) {
      result.push({
        src_prefix: (img.src || '').substring(0, 50),
        w: Math.round(rect.width),
        h: Math.round(rect.height)
      });
    }
  }
  // 也看看有没有 data:image 的 img
  var allImgs = document.querySelectorAll('img');
  var dataImgCount = 0;
  for (var i = 0; i < allImgs.length; i++) {
    if ((allImgs[i].src || '').indexOf('data:image') > -1) dataImgCount++;
  }
  return JSON.stringify({large_imgs: result, data_imgs: dataImgCount});
})()
""")
print("\n  封面状态:", r[:200] if r else 'empty')

print("\n✅ 完成")
s.close()
