# -*- coding: utf-8 -*-
import sys, json, time, urllib.request
sys.stdout.reconfigure(encoding='utf-8')

HOST = "localhost"
PORT = 9222

def get_targets():
    url = f'http://{HOST}:{PORT}/json'
    with urllib.request.urlopen(url) as r:
        return json.loads(r.read().decode())

page = None
for t in get_targets():
    if 'appmsg' in t.get('url', '') and 'action=edit' in t.get('url', ''):
        page = t
        break

import websocket
ws = websocket.create_connection(page['webSocketDebuggerUrl'])
ws.settimeout(30)

TITLE = '放春假的孩子开心到"模糊"，而家长还在焦虑"弯道超车"？'

# 方法: 使用DOMInput.setFileValue (如果支持)
print('[Step 1] 尝试使用DOMInput方法...')

# 先获取元素的nodeId
ws.send(json.dumps({
    'id': 1,
    'method': 'DOM.querySelector',
    'params': {'nodeId': 1, 'selector': '#title'}
}))
time.sleep(0.5)
response = ws.recv()
print('querySelector结果:', response[:200])

# 尝试直接执行setAttribute
ws.send(json.dumps({
    'id': 2,
    'method': 'Runtime.evaluate',
    'params': {
        'expression': f'''
        (function() {{
            var el = document.getElementById("title");
            if (!el) return "not found";
            
            // 清除现有内容
            el.value = "";
            
            // 逐字输入
            var text = "{TITLE}";
            for (var i = 0; i < text.length; i++) {{
                el.value += text[i];
            }}
            
            // 触发事件
            el.dispatchEvent(new InputEvent("input", {{ bubbles: true, data: el.value }}));
            
            return "value set: " + el.value.substring(0, 20);
        }})()
        '''
    }
}))
time.sleep(1)
response2 = ws.recv()
print('输入结果:', response2[:300])

# 验证
ws.send(json.dumps({
    'id': 3,
    'method': 'Runtime.evaluate',
    'params': {
        'expression': 'document.getElementById("title").value'
    }
}))
time.sleep(0.3)
response3 = ws.recv()
result = json.loads(response3)
value = result.get('result', {}).get('result', {}).get('value', '')
print('验证:', value[:50] if value else 'EMPTY')

ws.close()
