#!/usr/bin/env python3
"""stdio <-> central tasksd bridge.

A client that only speaks stdio MCP gets the central store anyway: one
JSON-RPC line in, one POST to the shared endpoint, one JSON line out. Used on
hosts whose MCP client build cannot open a Streamable-HTTP transport.
"""
import json
import os
import sys
import urllib.request

URL = os.environ.get("TASKSD_URL", "http://172.25.206.2:8781/mcp")


def send(payload):
    data = json.dumps(payload).encode()
    req = urllib.request.Request(URL, data=data, method="POST",
                                 headers={"Content-Type": "application/json",
                                          "Accept": "application/json, text/event-stream"})
    with urllib.request.urlopen(req, timeout=120) as r:
        raw = r.read()
    return raw


for line in sys.stdin:
    line = line.strip()
    if not line:
        continue
    try:
        msg = json.loads(line)
    except Exception:
        sys.stdout.write('{"jsonrpc":"2.0","id":null,"error":{"code":-32700,'
                         '"message":"parse error"}}\n')
        sys.stdout.flush()
        continue
    try:
        raw = send(msg)
    except Exception as e:
        if "id" not in msg:          # notification: nothing to answer
            continue
        sys.stdout.write(json.dumps({
            "jsonrpc": "2.0", "id": msg.get("id"),
            "error": {"code": -32603,
                      "message": "bridge: %s: %s" % (type(e).__name__, str(e)[:120])}}) + "\n")
        sys.stdout.flush()
        continue
    if not raw.strip():
        continue                     # notification: the server sent no body
    sys.stdout.write(raw.decode() if isinstance(raw, bytes) else raw)
    if not raw.endswith(b"\n"):
        sys.stdout.write("\n")
    sys.stdout.flush()
