"""Minimal FanDuel API client. Reads FANDUEL_API_KEY from the environment.

    pip install requests
    FANDUEL_API_KEY=fd_... python fanduel_api.py

Starts with five rows, so a first run costs one request. FanDuel API is an independent data service operated by
FF API Inc. It is not affiliated with, endorsed by or sponsored by FanDuel.
"""
import os
import time

import requests

BASE = "https://fanduelapi.com/api/v1"
SESSION = requests.Session()
SESSION.headers["Authorization"] = f"Bearer {os.environ['FANDUEL_API_KEY']}"


def get(path, **params):
    """GET one endpoint and return the whole body, waiting out a 429 with its Retry-After."""
    while True:
        r = SESSION.get(f"{BASE}{path}", params=params, timeout=15)
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", "5")))
            continue
        r.raise_for_status()
        return r.json()


def changes_since(cursor="0"):
    """Yield every change after a cursor, forever, one request per poll."""
    while True:
        body = get("/changes", since=cursor, limit=500)
        yield from body["data"]
        cursor = body["meta"].get("next_cursor", cursor)
        if not body["data"]:
            time.sleep(10)


if __name__ == "__main__":
    body = get("/props", sport="nba", limit=5)
    print("plan", body["meta"]["plan"], "delay", body["meta"]["delay_seconds"], "s")
    for p in body["data"]:
        print(f"{p['player']:<26} {p['stat']:<10} {p['line']!s:>6}  {p['over_american']!s:>5} / {p['under_american']!s:>5}")
