"""
test_ws_js.py — 模拟 JS（WebView 内）端

连接 WS Hub，订阅 "js" 话题。
接收来自 Agent 的消息（发到 "js" 话题）。
发消息到 "agent" 话题（Agent 端会收到）。

用法:
  python test_ws_js.py [--port 9099]
"""
import sys
import json
import time
import websocket

PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 9099
URL = f"ws://127.0.0.1:{PORT}"

def on_message(ws, msg):
    print(f"[JS] <<< {msg}")
    # 收到 Agent 消息后，回复一个 DOM 描述
    reply = json.dumps({"type": "dom_description", "title": "Bing", "body": "..."})
    ws.send(reply)
    print(f"[JS] >>> {reply}")

def on_open(ws):
    print(f"[JS] Connected to {URL}")

def on_error(ws, err):
    print(f"[JS] ERROR: {err}")

def on_close(ws, status, msg):
    print(f"[JS] Closed (status={status}, msg={msg})")

ws = websocket.WebSocketApp(
    URL,
    on_message=on_message,
    on_open=on_open,
    on_error=on_error,
    on_close=on_close
)

print(f"[JS] Connecting to {URL}...")
ws.run_forever()
