#!/usr/bin/env python3
"""ApiDatasets MCP stdio bridge.

This optional bridge lets local MCP clients that only support stdio talk to
the hosted ApiDatasets Streamable HTTP MCP endpoint.

Environment:
  APIDATASETS_API_KEY   Optional. Enables production MCP mode.
  APIDATASETS_MCP_URL   Optional. Defaults to https://apidatasets.com/mcp
"""

from __future__ import annotations

import json
import os
import sys
import urllib.error
import urllib.request


MCP_URL = os.environ.get("APIDATASETS_MCP_URL", "https://apidatasets.com/mcp")
API_KEY = os.environ.get("APIDATASETS_API_KEY", "")


def forward(message: dict) -> dict:
    method = message.get("method", "")
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json, text/event-stream",
        "MCP-Protocol-Version": "2025-06-18",
    }
    if method:
        headers["Mcp-Method"] = method
    params = message.get("params") or {}
    if method == "tools/call" and params.get("name"):
        headers["Mcp-Name"] = str(params["name"])
    if API_KEY:
        headers["Authorization"] = f"Bearer {API_KEY}"

    request = urllib.request.Request(
        MCP_URL,
        data=json.dumps(message, separators=(",", ":")).encode("utf-8"),
        headers=headers,
        method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=60) as response:
            raw = response.read().decode("utf-8")
    except urllib.error.HTTPError as exc:
        raw = exc.read().decode("utf-8")
    if not raw:
        return {"jsonrpc": "2.0", "id": message.get("id"), "result": {}}
    return json.loads(raw)


def main() -> None:
    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        try:
            message = json.loads(line)
            result = forward(message)
        except Exception as exc:
            result = {
                "jsonrpc": "2.0",
                "id": None,
                "error": {"code": -32603, "message": f"ApiDatasets stdio bridge error: {exc}"},
            }
        sys.stdout.write(json.dumps(result, separators=(",", ":")) + "\n")
        sys.stdout.flush()


if __name__ == "__main__":
    main()
