#!/usr/bin/env python3
"""
CLI shim: call a relay MCP tool via raw SSE protocol.
Usage:
  python3 call.py read_messages '{"for":"pm"}'
  python3 call.py post_message '{"from":"pm","to":"dev-a","kind":"directive","body":"..."}'
  python3 call.py list_pending '{"for":"pm"}'
"""
import sys, json, threading, requests, time

BASE = "http://localhost:7331"
tool_name = sys.argv[1]
args = json.loads(sys.argv[2]) if len(sys.argv) > 2 else {}

result = {"done": False, "value": None}
endpoint_url = {"url": None}
msg_id = 1

def read_sse():
    with requests.get(f"{BASE}/sse", stream=True, timeout=15) as r:
        for line in r.iter_lines(decode_unicode=True):
            if not line:
                continue
            if line.startswith("data:"):
                data = line[5:].strip()
                if not endpoint_url["url"] and data.startswith("/message"):
                    endpoint_url["url"] = BASE + data
                elif endpoint_url["url"]:
                    try:
                        payload = json.loads(data)
                        if payload.get("id") == msg_id:
                            result["value"] = payload
                            result["done"] = True
                            return
                    except json.JSONDecodeError:
                        pass

t = threading.Thread(target=read_sse, daemon=True)
t.start()

# Wait for endpoint
for _ in range(50):
    if endpoint_url["url"]:
        break
    time.sleep(0.1)
if not endpoint_url["url"]:
    print(json.dumps({"error": "no endpoint received"}))
    sys.exit(1)

# Send initialize
init_payload = {
    "jsonrpc": "2.0", "id": 0, "method": "initialize",
    "params": {
        "protocolVersion": "2024-11-05",
        "capabilities": {},
        "clientInfo": {"name": "relay-cli", "version": "0.1.0"}
    }
}
requests.post(endpoint_url["url"], json=init_payload, timeout=5)

# Send tools/call
call_payload = {
    "jsonrpc": "2.0", "id": msg_id, "method": "tools/call",
    "params": {"name": tool_name, "arguments": args}
}
requests.post(endpoint_url["url"], json=call_payload, timeout=5)

# Wait for result
for _ in range(100):
    if result["done"]:
        break
    time.sleep(0.1)

if result["done"]:
    content = result["value"].get("result", {}).get("content", [])
    for item in content:
        if item.get("type") == "text":
            print(item["text"])
else:
    print(json.dumps({"error": "timeout waiting for response"}))
    sys.exit(1)
