/**
 * StashGamma MCP endpoint — programmatic Node client using the official
 * @modelcontextprotocol/sdk's Streamable HTTP client. Use this when you're building your
 * own agent/script and want to call the `get_eod_data` tool directly, without a chat UI
 * (Claude Desktop/Code) in the loop.
 *
 *   npm install
 *   export STASHGAMMA_API_KEY=sg_live_...
 *   node node_client.mjs QQQ 2026-07-01 2026-08-01
 *
 * Same auth, same rate-limit bucket as the REST API — see ../node/eod-quickstart.mjs
 * for the plain-REST equivalent, and https://www.stashgamma.com/developer-docs#mcp for
 * the full protocol reference.
 */
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";

const MCP_URL = "https://www.stashgamma.com/api/dataapi/mcp";

async function getEodData(symbol, from, to, apiKey) {
  const transport = new StreamableHTTPClientTransport(new URL(MCP_URL), {
    requestInit: { headers: { "X-Api-Key": apiKey } },
  });

  const client = new Client({ name: "stashgamma-example-client", version: "1.0.0" });
  await client.connect(transport);

  try {
    const args = { symbol };
    if (from) args.from = from;
    if (to) args.to = to;

    const result = await client.callTool({ name: "get_eod_data", arguments: args });

    if (result.isError) {
      // Rate-limited, bad symbol, no data, etc. — the reason is in the text content,
      // not a thrown protocol error, so your script can decide how to react.
      throw new Error(result.content[0].text);
    }

    return JSON.parse(result.content[0].text);
  } finally {
    await client.close();
  }
}

const [symbol = "QQQ", from = "2026-07-01", to = "2026-08-01"] = process.argv.slice(2);
const apiKey = process.env.STASHGAMMA_API_KEY;
if (!apiKey) {
  console.error(
    "Set STASHGAMMA_API_KEY first — get a free key at https://www.stashgamma.com/profile?tab=developer"
  );
  process.exit(1);
}

const data = await getEodData(symbol, from, to, apiKey);
console.log(`${data.symbol}: ${data.count} bars`);
console.log(data.bars.slice(0, 5));
