/**
 * StashGamma EOD Data API — Java quickstart. Stdlib only (Java 11+), no third-party
 * HTTP or JSON library required for this minimal version.
 *
 *   export STASHGAMMA_API_KEY=sg_live_...
 *   javac StashGammaEodExample.java
 *   java StashGammaEodExample QQQ 2026-07-01 2026-08-01
 *
 * Docs: https://www.stashgamma.com/developer-docs
 *
 * For anything beyond a quick script, pair this with Jackson or Gson to deserialize
 * the response body into a typed record instead of the manual "bars" substring
 * extraction below (kept dependency-free here on purpose).
 */
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class StashGammaEodExample {
    private static final String BASE_URL = "https://www.stashgamma.com/api/dataapi/v1";

    public static void main(String[] args) throws Exception {
        String symbol = args.length > 0 ? args[0] : "QQQ";
        String from = args.length > 1 ? args[1] : "2026-07-01";
        String to = args.length > 2 ? args[2] : "2026-08-01";
        String apiKey = System.getenv("STASHGAMMA_API_KEY");
        if (apiKey == null || apiKey.isBlank()) {
            System.err.println("Set STASHGAMMA_API_KEY first — get a free key at "
                + "https://www.stashgamma.com/profile?tab=developer");
            System.exit(1);
        }

        String body = getEodBars(symbol, from, to, apiKey);
        System.out.println(body);
    }

    /** Fetch daily OHLCV bars for `symbol`, retrying once on a 429 using Retry-After. */
    static String getEodBars(String symbol, String from, String to, String apiKey) throws Exception {
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

        String url = String.format("%s/eod/%s?from=%s&to=%s", BASE_URL, symbol, from, to);
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("X-Api-Key", apiKey)
            .timeout(Duration.ofSeconds(10))
            .GET()
            .build();

        for (int attempt = 0; attempt <= 3; attempt++) {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() == 429 && attempt < 3) {
                int retryAfter = response.headers().firstValueAsLong("Retry-After").orElse(5L).intValue();
                System.err.printf("Rate limited, retrying in %ds...%n", retryAfter);
                Thread.sleep(retryAfter * 1000L);
                continue;
            }

            if (response.statusCode() != 200) {
                throw new RuntimeException("HTTP " + response.statusCode() + ": " + response.body());
            }

            return response.body(); // {"symbol":"QQQ","from":"...","to":"...","count":N,"bars":[...]}
        }

        throw new RuntimeException("Still rate-limited after retries");
    }
}
