# Morning regime brief: Dealer gamma for SPY, QQQ and IWM plus the VIX, in one screen before the open.
# https://apexvol.com/developers/recipes/morning-regime-brief
import os
import sys

import requests

# One token, any paid or trial plan: Account, then API Access.
TOKEN = os.environ.get("APEXVOL_API_TOKEN") or sys.exit("set APEXVOL_API_TOKEN")
BASE = os.environ.get("APEXVOL_API_URL", "https://apexvol.com") + "/api/mcp/data"
S = requests.Session()
S.headers["Authorization"] = f"Bearer {TOKEN}"


def get(path, **params):
    r = S.get(BASE + path, params=params, timeout=90)
    body = r.json()
    if not body.get("success"):
        sys.exit(f"{path}: HTTP {r.status_code}: {body.get('error')}")
    return body["data"]


symbols = "SPY,QQQ,IWM"
gex = get("/batch/gex", tickers=symbols, strikes_around=5)
vix = get("/vix")

print(f"VIX {vix['price']:.2f} ({vix['change_pct']:+.1f}% on the day)")
print()
print(f"{'':6}{'spot':>9}{'net gamma ($bn)':>17}{'flip':>9}{'call wall':>11}{'put wall':>10}  regime")
for sym in symbols.split(","):
    d = gex["results"].get(sym)
    if not d:
        print(f"{sym:6} {gex['errors'].get(sym)}")
        continue
    lv = d.get("key_levels") or {}
    flip = d.get("flip_level")
    net_bn = (d.get("total_gex") or 0) / 1e9
    regime = "positive: pin and fade" if net_bn > 0 else "negative: trend and widen"
    fmt = lambda v: f"{v:,.0f}" if isinstance(v, (int, float)) else "none"
    print(f"{sym:6}{d['stock_price']:>9,.2f}{net_bn:>17,.2f}{fmt(flip):>9}"
          f"{fmt(lv.get('call_wall')):>11}{fmt(lv.get('put_wall')):>10}  {regime}")
print()
print("Levels are aggregate across listed expirations; pass expiration=YYYY-MM-DD for one expiry.")
