#!/usr/bin/env python3
"""
pub.py — ws_hub 测试客户端（给 AI agent 用，非交互）

用法：
  python pub.py '{"action":"describe"}'
  python pub.py '{"action":"click","params":{"selector":"#btn"}}'
  python pub.py '{"action":"type","params":{"selector":"#input","text":"hello"}}'

自动连接 ws://127.0.0.1:9099，订阅 agent，发送指令到 js，打印回复后退出。
"""

import sys
import json
import websocket

HOST = "127.0.0.1"
PORT = 9099


def main():
    if len(sys.argv) < 2:
        print("用法: python pub.py '<json指令>'")
        print("示例: python pub.py '{\"action\":\"describe\"}'")
        sys.exit(1)

    try:
        msg = json.loads(sys.argv[1])
    except json.JSONDecodeError as e:
        print(f"[错误] 无效 JSON: {e}", flush=True)
        sys.exit(1)

    url = f"ws://{HOST}:{PORT}"
    try:
        ws = websocket.create_connection(url, timeout=10)
    except Exception as e:
        print(f"[错误] 连接 ws_hub 失败: {e}", flush=True)
        sys.exit(1)

    # 订阅 agent 话题
    ws.send(json.dumps({"type": "subscribe", "topic": "agent"}))

    # 发布指令到 js 话题
    payload = {"type": "publish", "topic": "js", "data": msg}
    ws.send(json.dumps(payload))
    print(f"[→] 已发送: {json.dumps(msg, ensure_ascii=False)}", flush=True)

    # 等待回复（最多 30 秒）
    ws.settimeout(30)
    try:
        raw = ws.recv()
        try:
            data = json.loads(raw)
            print(json.dumps(data, ensure_ascii=False, indent=2), flush=True)
        except json.JSONDecodeError:
            print(raw, flush=True)
    except Exception as e:
        print(f"[超时] 未收到回复: {e}", flush=True)
    finally:
        ws.close()


if __name__ == "__main__":
    main()
