# -*- coding: utf-8 -*-
import sys, socket, json, time, base64, urllib.request, subprocess
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': '''
        (function() {
            var btn = document.querySelector('#js_save, .js_save, button[data-action="save"]');
            if (btn) {
                btn.click();
                return 'clicked';
            }
            return 'not found';
        })()
        '''}}))
    time.sleep(0.5)
    
    # 等待保存完成
    print('[Step 2] 等待保存完成...')
    for i in range(10):
        time.sleep(1)
        ws.send(json.dumps({'id': 10+i, 'method': 'Runtime.evaluate', 'params': {
            'expression': 'document.querySelector(".weui-desktop-toast__content") ? document.querySelector(".weui-desktop-toast__content").innerText : ""'}}))
        try:
            result = ws.recv()
            data = json.loads(result)
            msg = data.get('result', {}).get('result', {}).get('value', '')
            if '保存' in msg or '成功' in msg:
                print(f'  保存状态: {msg}')
                break
        except:
            pass
        print(f'  等待中... {i+1}/10')
    
    # 截图
    print('[Step 3] 截图...')
    ws.send(json.dumps({'id': 100, 'method': 'Page.captureScreenshot', 'params': {}}))
    time.sleep(1)
    try:
        result = ws.recv()
        data = json.loads(result)
        img_data = data.get('result', {}).get('data', '')
        if img_data:
            with open('after_save.png', 'wb') as f:
                f.write(base64.b64decode(img_data))
            print('  截图已保存: after_save.png')
    except Exception as e:
        print(f'  截图失败: {e}')
    
    ws.close()
    print('[DONE] 草稿保存完成')
