#!/usr/bin/env node
import { isIP as l } from "node:net";
import { StreamableHTTPServerTransport as f } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import m from "dotenv";
import a from "express";
import { g as d } from "./mcp-server-Bxbg2tUi.js";
import { r as T } from "./require-valid-todoist-token-BBIEpLjl.js";
m.config({ quiet: !0 });
const s = Number.parseInt(process.env.PORT || "3000", 10), v = process.env.HOST || "127.0.0.1", i = u(v);
function u(r) {
  return r.startsWith("[") && r.endsWith("]") ? r.slice(1, -1) : r;
}
function O(r) {
  return r === "0.0.0.0" || r === "::" ? "localhost" : p(r);
}
function p(r) {
  return l(r) === 6 ? `[${r}]` : r;
}
function S(r) {
  return r = u(r), r === "localhost" || r === "::1" || r === "0:0:0:0:0:0:0:1" ? !0 : l(r) === 4 ? r.split(".")[0] === "127" : !1;
}
function I() {
  const r = process.env.TODOIST_BASE_URL, c = process.env.TODOIST_API_KEY;
  c || (console.error("Error: TODOIST_API_KEY environment variable is required"), process.exit(1));
  const o = a();
  o.use(a.json()), o.get("/health", (e, t) => {
    t.json({ status: "ok" });
  }), o.post(
    "/mcp",
    T({ type: "static", apiKey: c, baseUrl: r }),
    async (e, t) => {
      try {
        const n = new f({
          sessionIdGenerator: void 0
        });
        await d({ todoistApiKey: c, baseUrl: r }).connect(n), await n.handleRequest(e, t, e.body);
      } catch (n) {
        console.error("[Error] Request handling failed:", n), t.status(500).json({
          jsonrpc: "2.0",
          error: {
            code: -32603,
            message: "Internal server error"
          },
          id: null
        });
      }
    }
  ), o.get("/mcp", (e, t) => {
    t.status(405).set("Allow", "POST").send("Method Not Allowed");
  }), o.listen(s, i, () => {
    const e = O(i);
    console.error(`Todoist MCP HTTP Server started on ${p(i)}:${s}`), console.error(`MCP endpoint: http://${e}:${s}/mcp`), console.error(`Health check: http://${e}:${s}/health`), S(i) || console.error(
      "Warning: todoist-mcp-http is reachable from other hosts. Protect this service with trusted network/auth controls because requests run with TODOIST_API_KEY."
    );
  });
}
I();
