# -*- coding: utf-8 -*-
"""
百家号 - 插入文首图片 + 封面图片
===================================
文首图：直接嵌入 HTML（用 img 标签）
封面图：触发 file 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"

def get_latest_image():
    d = r'D:\wxpic'
    exts = ['*.jpg','*.jpeg','*.png','*.gif','*.webp']
    imgs = []
    for e in exts: imgs.extend(glob.glob(os.path.join(d, e)))
    return max(imgs, key=os.path.getmtime) if imgs else None

IMG_PATH = get_latest_image()
print("[INFO] 图片:", IMG_PATH)

# 读图片并转 base64
with open(IMG_PATH, 'rb') as f:
    IMG_B64 = b64encode(f.read()).decode('utf-8')
ext = os.path.splitext(IMG_PATH)[1].lower()
IMG_MIME = 'image/jpeg' if ext in ['.jpg','.jpeg'] else 'image/png'
IMG_NAME = 'cover_' + str(int(time.time())) + ext
print("[INFO] 大小:", len(IMG_B64), "bytes, MIME:", IMG_MIME)

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

# ── Part 1: 文首图片 ──────────────────────────────────────────────────────
print("[Part 1] 插入文首图片（HTML img 标签）...")
# 把 base64 图片注入到 window
cdp(s, "window.__IMG_B64__ = '%s'" % IMG_B64, timeout=5)
cdp(s, "window.__IMG_MIME__ = '%s'" % IMG_MIME, timeout=5)
cdp(s, "window.__IMG_NAME__ = '%s'" % IMG_NAME, timeout=5)

r = cdp(s, """
var b64 = window.__IMG_B64__ || '';
var mime = window.__IMG_MIME__ || 'image/jpeg';
var name = window.__IMG_NAME__ || 'img.jpg';
if (!b64) { 'no_b64'; }
else {
  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], name, {type: mime});

  // 找 UE 实例
  var ins = window.UE_V2 && window.UE_V2.instants;
  var result = 'no_instants';
  if (ins) {
    var keys = Object.keys(ins);
    for (var i = 0; i < keys.length; i++) {
      var inst = ins[keys[i]];
      if (inst && inst.key === 'ueditor') {
        try {
          var imgHtml = '<p style="text-align:center;margin:16px 0"><img src="data:' + mime + ';base64,' + b64 + '" style="max-width:100%;height:auto;border-radius:4px" alt="封面图"/></p>';
          inst.setContent(imgHtml + inst.getContent());
          result = 'ok:len=' + inst.getContent().length;
        } catch(e) {
          result = 'err:' + e.message;
        }
        break;
      }
    }
  }
  result;
}
""", timeout=30)
print("  文首图:", r[:100] if r else 'empty')
time.sleep(1)

# ── Part 2: 封面图片 ─────────────────────────────────────────────────────
print("\n[Part 2] 上传封面图片...")

# 方法：通过 file input 直接注入 File 对象
r = cdp(s, """
(function() {
  // 找"选择封面"相关的 input[type=file]
  var inputs = document.querySelectorAll('input[type=file]');
  var info = [];
  for (var i = 0; i < inputs.length; i++) {
    var inp = inputs[i];
    var rect = inp.getBoundingClientRect();
    info.push({
      index: i,
      accept: inp.accept,
      display: window.getComputedStyle(inp).display,
      visible: rect.width > 0 && rect.height > 0,
      w: Math.round(rect.width),
      h: Math.round(rect.height)
    });
  }
  return JSON.stringify(info);
})()
""")
print("  file inputs:", r[:200] if r else 'empty')

# 注入图片到 file input
r = cdp(s, """
(function() {
  var b64 = window.__IMG_B64__ || '';
  var mime = window.__IMG_MIME__ || 'image/jpeg';
  var name = window.__IMG_NAME__ || 'img.jpg';
  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], name, {type: mime});

  // 找所有 input[type=file]
  var inputs = document.querySelectorAll('input[type=file]');
  var result = 'no_file_input';
  for (var i = 0; i < inputs.length; i++) {
    var inp = inputs[i];
    var s = window.getComputedStyle(inp);
    if (s.display !== 'none' && s.visibility !== 'hidden') {
      try {
        // 使用 DataTransfer 来设置 files
        var dt = new DataTransfer();
        dt.items.add(file);
        Object.defineProperty(inp, 'files', {
          value: dt.files,
          writable: true,
          configurable: true
        });
        // 触发 change 事件
        var evt = new Event('change', {bubbles: true, cancelable: false});
        inp.dispatchEvent(evt);
        result = 'ok:input_index=' + i + ',file_name=' + name;
      } catch(e) {
        result = 'err:' + e.message;
      }
      break;
    }
  }
  return result;
})()
""", timeout=20)
print("  封面图注入:", r[:100] if r else 'empty')
time.sleep(3)

# 检查结果
r = cdp(s, "var els=document.querySelectorAll('*');var out=[];for(var el of els){var t=(el.innerText||'').trim();if(t.match(/字数/)&&t.match(/\\d+/))out.push(t)}out.join(' | ')")
print("\n[字数]", r[:200] if r else 'empty')

print("\n✅ 图片插入完成，请在浏览器中确认")
s.close()
