"""
test_ws_agent.py — 模拟 Agent 端

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

用法:
  python test_ws_agent.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"[AGENT] <<< {msg}")

def on_open(ws):
    print(f"[AGENT] Connected to {URL}")
    # 发送一条测试消息到 js 话题
    payload = json.dumps({"type": "navigate", "url": "https://www.bing.com"})
    ws.send(payload)
    print(f"[AGENT] >>> {payload}")

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

def on_close(ws, status, msg):
    print(f"[AGENT] 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"[AGENT] Connecting to {URL}...")
ws.run_forever()
