# -*- coding: utf-8 -*-
import sys, socket, 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

if not page:
    print('[ERR] 未找到编辑页面')
    sys.exit(1)

print(f'[OK] 页面ID: {page["id"][:20]}...')

# 使用CDP协议直接设置值
import websocket
ws = websocket.create_connection(page['webSocketDebuggerUrl'])
ws.settimeout(30)

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

# 方法1: 直接设置value并触发input事件
print('[Step 1] 设置标题...')
ws.send(json.dumps({
    'id': 1,
    'method': 'Runtime.evaluate',
    'params': {
        'expression': f'''
        (function() {{
            var el = document.getElementById("title");
            if (!el) return "element not found";
            
            // 设置值
            el.value = "{TITLE}";
            
            // 触发input事件
            var event = new Event("input", {{ bubbles: true }});
            el.dispatchEvent(event);
            
            // 触发change事件
            var changeEvent = new Event("change", {{ bubbles: true }});
            el.dispatchEvent(changeEvent);
            
            return "set success, current value: " + el.value;
        }})()
        '''
    }
}))

time.sleep(0.5)
response = ws.recv()
result = json.loads(response)
print('结果:', result.get('result', {}).get('result', {}).get('value', 'NO_VALUE'))

# 验证
print('[Step 2] 验证标题...')
ws.send(json.dumps({
    'id': 2,
    'method': 'Runtime.evaluate',
    'params': {
        'expression': 'document.getElementById("title").value'
    }
}))

time.sleep(0.3)
response2 = ws.recv()
result2 = json.loads(response2)
title_value = result2.get('result', {}).get('result', {}).get('value', '')
print('当前标题:', title_value[:50] if title_value else 'EMPTY')

ws.close()

if title_value:
    print('[OK] 标题设置成功')
else:
    print('[ERR] 标题设置失败')
