"""Two-call Free equity evaluation. Python 3.10+, no third-party packages.
Set FLASHALPHA_API_KEY before running. This makes real, quota-counted API calls.
"""
import json
import os
from datetime import datetime, timezone
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen


def get(path, params=None):
    key = os.environ.get("FLASHALPHA_API_KEY")
    if not key:
        raise RuntimeError("Set FLASHALPHA_API_KEY to your API key.")
    url = "https://lab.flashalpha.com" + path
    if params:
        url += "?" + urlencode(params)
    try:
        with urlopen(Request(url, headers={"X-Api-Key": key}), timeout=20) as response:
            return json.load(response)
    except HTTPError as error:
        hints = {401: "Check your API key.", 403: "Check symbol, expiry and plan access.",
                 429: "Request allowance or concurrency limit reached; wait before retrying."}
        raise RuntimeError(f"HTTP {error.code}. " + hints.get(error.code, "API request failed.")) from None
    except (URLError, TimeoutError, json.JSONDecodeError):
        raise RuntimeError("No usable API response; check service status and retry later.") from None


def main():
    symbol = "AAPL"
    options = get(f"/v1/options/{symbol}")
    # UTC is a conservative date cutoff: any later date is also after today in New York.
    # Near midnight UTC this can skip an otherwise eligible next-day NY expiration.
    today = datetime.now(timezone.utc).date().isoformat()
    expiries = sorted(row["expiration"] for row in options.get("expirations", [])
                      if row.get("expiration", "") > today)
    if not expiries:
        raise RuntimeError("No listed future expiry returned. Do not invent an expiration.")
    expiry = expiries[0]
    result = get(f"/v1/exposure/gex/{symbol}", {"expiration": expiry})
    print(f"Symbol: {symbol}; expiration: {expiry}")
    print(f"Response as_of: {result.get('as_of', 'not supplied')}")
    print(f"Net GEX ($ per 1% move): {result.get('net_gex')}")
    print(f"Gamma flip: {result.get('gamma_flip')}; status: {result.get('gamma_flip_status', 'not supplied')}")
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    try:
        main()
    except RuntimeError as error:
        raise SystemExit(str(error))
