# -*- 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 = '放春假的孩子开心到"模糊"，而家长还在焦虑"弯道超车"？'

# 先点击标题区域获得焦点
print('[Step 1] 点击标题区域...')
ws.send(json.dumps({
    'id': 1,
    'method': 'Runtime.evaluate',
    'params': {
        'expression': '''
        (function() {
            var el = document.getElementById("title");
            if (!el) return "not found";
            el.focus();
            el.click();
            return "focused";
        })()
        '''
    }
}))
time.sleep(0.5)
ws.recv()

# 然后填入标题
print('[Step 2] 填入标题...')
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 = "{TITLE}";
            el.dispatchEvent(new Event("input", {{ bubbles: true }}));
            return "set";
        }})()
        '''
    }
}))
time.sleep(0.5)
ws.recv()

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

ws.close()

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