# -*- 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)

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

# 找"选择封面"按钮
print("[探测] 选择封面按钮...")
r = cdp(s, """
(function() {
  var all = document.querySelectorAll('*');
  var result = [];
  for (var el of all) {
    var t = (el.innerText || '').trim();
    if (t === '选择封面' || t.includes('选择封面')) {
      var rect = el.getBoundingClientRect();
      var s = window.getComputedStyle(el);
      result.push({
        tag: el.tagName,
        class: el.className.substring(0,40),
        text: t,
        x: Math.round(rect.left + rect.width/2),
        y: Math.round(rect.top + rect.height/2),
        display: s.display,
        visible: rect.width > 0 && rect.height > 0
      });
    }
  }
  return JSON.stringify(result);
})()
""")
print("  按钮:", r[:200] if r else 'empty')

# 找所有 input[type=file]
print("\n[探测] 所有 input[type=file]...")
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 rect = inp.getBoundingClientRect();
    var s = window.getComputedStyle(inp);
    result.push({
      index: i,
      accept: inp.accept,
      display: s.display,
      width: Math.round(rect.width),
      height: Math.round(rect.height),
      parent: inp.parentElement ? inp.parentElement.tagName + '.' + inp.parentElement.className.substring(0,20) : ''
    });
  }
  // 也看看有没有 accept="image/*" 的 input
  var allInputs = document.querySelectorAll('input');
  for (var j = 0; j < allInputs.length; j++) {
    var inp2 = allInputs[j];
    var acc2 = inp2.getAttribute('accept') || '';
    if (acc2.includes('image')) {
      var rect2 = inp2.getBoundingClientRect();
      var s2 = window.getComputedStyle(inp2);
      result.push({
        index: 'image:' + j,
        accept: acc2,
        display: s2.display,
        width: Math.round(rect2.width),
        height: Math.round(rect2.height),
        parent: inp2.parentElement ? inp2.parentElement.tagName + '.' + inp2.parentElement.className.substring(0,30) : ''
      });
    }
  }
  return JSON.stringify(result);
})()
""")
print("  file inputs:", r[:300] if r else 'empty')

# 看看封面区域附近的 DOM 结构
print("\n[探测] 封面区域附近 DOM...")
r = cdp(s, """
(function() {
  var all = document.querySelectorAll('*');
  var result = [];
  for (var el of all) {
    var t = (el.innerText || '').trim();
    if (t === '选择封面' || t === '封面' || t === '单图' || t === '三图') {
      var rect = el.getBoundingClientRect();
      result.push({
        tag: el.tagName,
        class: el.className.substring(0,40),
        text: t,
        x: Math.round(rect.left + rect.width/2),
        y: Math.round(rect.top + rect.height/2),
        children: el.children.length
      });
    }
  }
  return JSON.stringify(result);
})()
""")
print("  封面区域:", r[:300] if r else 'empty')

s.close()
