# Unusual flow today: The session's unusual options prints for a name, with volume against open interest.
# https://apexvol.com/developers/recipes/flow-unusual-today
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"]


SYMBOL = "NVDA"
d = get(f"/flow/{SYMBOL}", limit=10, detail="compact")
s = d.get("summary") or {}
print(f"{SYMBOL} flow ({d.get('data_freshness')}), spot {d.get('stock_price')}")
print(f"calls {s.get('total_call_volume', 0):,.0f} contracts / ${s.get('total_call_premium', 0)/1e6:,.1f}M   "
      f"puts {s.get('total_put_volume', 0):,.0f} / ${s.get('total_put_premium', 0)/1e6:,.1f}M   "
      f"put/call {s.get('put_call_ratio')}   {s.get('sentiment')}")
if d.get("message"):
    print(d["message"])
print()
rows = sorted(d.get("unusual_activity") or [], key=lambda r: -(r.get("premium") or 0))
print(f"{'type':5}{'strike':>8}{'expiry':>12}{'dte':>5}{'volume':>9}{'OI':>8}{'vol/OI':>8}{'premium $M':>12}")
for r in rows[:10]:
    print(f"{r['type']:5}{r['strike']:>8,.1f}{r['expiration']:>12}{r['dte']:>5}{r['volume']:>9,.0f}"
          f"{r['oi']:>8,.0f}{r['volume_oi_ratio']:>8.1f}{r['premium']/1e6:>12.2f}")
if not rows:
    print("no rows flagged unusual in this session")
