# -*- coding: utf-8 -*-
import sys, socket, json, time, urllib.request, base64, os
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())

def find_editor_page():
    for t in get_targets():
        if 'appmsg' in t.get('url', ''):
            return t
    return None

if __name__ == '__main__':
    page = find_editor_page()
    if not page:
        print('[ERROR] 未找到公众号编辑页面，请先打开编辑界面')
        sys.exit(1)
    
    ws_url = page['webSocketDebuggerUrl']
    print(f'[OK] 找到编辑页面: {page["id"][:16]}...')
    
    import websocket
    ws = websocket.create_connection(ws_url)
    ws.settimeout(30)
    print('[OK] WebSocket 已连接')
    
    # 填写作者
    print('[Step 1] 填写作者...')
    ws.send(json.dumps({'id': 1, 'method': 'Runtime.evaluate', 'params': {
        'expression': 'document.getElementById("author").value = "升学有陆"'}}))
    time.sleep(0.5)
    print('  作者已填入: 升学有陆')
    
    # 开启原创声明
    print('[Step 2] 开启原创声明...')
    ws.send(json.dumps({'id': 2, 'method': 'Runtime.evaluate', 'params': {
        'expression': '''
        (function() {
            var cb = document.querySelector('#js_original_checkbox, .js_original_checkbox, input[name="original"]');
            if (cb && !cb.checked) {
                cb.click();
                return 'clicked';
            }
            return cb ? 'already checked' : 'not found';
        })()
        '''}}))
    time.sleep(0.5)
    result = ws.recv()
    print('  原创声明已开启')
    
    ws.close()
    print('[DONE] 作者和原创声明设置完成')
