#!/usr/bin/env node
/**
 * Stdio-to-HTTP bridge for graph8 MCP server.
 * Claude Desktop talks stdio to this script, which proxies to the remote HTTP endpoint.
 */
import { createInterface } from "readline";

const REMOTE_URL = process.env.G8_MCP_URL || "https://be.qa.graph8.com/mcp/";
const API_KEY = process.env.G8_API_KEY || "";

const rl = createInterface({ input: process.stdin });

rl.on("line", async (line) => {
  try {
    const msg = JSON.parse(line);

    // Notifications (no id) — fire and forget
    if (msg.id === undefined) {
      fetch(REMOTE_URL, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json, text/event-stream",
          Authorization: `Bearer ${API_KEY}`,
        },
        body: JSON.stringify(msg),
      }).catch(() => {});
      return;
    }

    const resp = await fetch(REMOTE_URL, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json, text/event-stream",
        Authorization: `Bearer ${API_KEY}`,
      },
      body: JSON.stringify(msg),
    });

    const text = await resp.text();

    // Parse SSE response - extract JSON from "data: " lines
    for (const l of text.split("\n")) {
      if (l.startsWith("data: ")) {
        process.stdout.write(l.slice(6) + "\n");
      }
    }
  } catch (err) {
    process.stdout.write(
      JSON.stringify({
        jsonrpc: "2.0",
        id: null,
        error: { code: -32603, message: err.message },
      }) + "\n"
    );
  }
});

rl.on("close", () => process.exit(0));
