/**
 * StashGamma EOD Data API — Node.js quickstart. No dependencies (Node 18+ has fetch built in).
 *
 *   export STASHGAMMA_API_KEY=sg_live_...
 *   node eod-quickstart.mjs QQQ 2026-07-01 2026-08-01
 *
 * Docs: https://www.stashgamma.com/developer-docs
 */
const BASE_URL = "https://www.stashgamma.com/api/dataapi/v1";

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

/** Fetch daily OHLCV bars for `symbol`, retrying once on a 429 using Retry-After. */
async function getEodBars(symbol, from, to, apiKey = process.env.STASHGAMMA_API_KEY, maxRetries = 3) {
  const params = new URLSearchParams();
  if (from) params.set("from", from);
  if (to) params.set("to", to);

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    const res = await fetch(`${BASE_URL}/eod/${symbol}?${params}`, {
      headers: { "X-Api-Key": apiKey },
    });

    if (res.status === 429 && attempt < maxRetries) {
      const retryAfter = Number(res.headers.get("Retry-After") ?? "5");
      console.error(
        `Rate limited, retrying in ${retryAfter}s ` +
          `(${res.headers.get("X-RateLimit-Remaining-Hour") ?? "?"} left this hour)...`
      );
      await sleep(retryAfter * 1000);
      continue;
    }

    if (!res.ok) {
      const body = await res.json().catch(() => ({}));
      throw new Error(`${res.status}: ${body.error ?? res.statusText}`);
    }

    const { bars } = await res.json();
    return bars;
  }

  throw new Error(`Still rate-limited after ${maxRetries} retries`);
}

const [symbol = "QQQ", from = "2026-07-01", to = "2026-08-01"] = process.argv.slice(2);

const bars = await getEodBars(symbol, from, to);
console.log(`${symbol}: ${bars.length} bars`);
console.log(bars.slice(0, 5));
