import json
import os
import time
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen

API_KEY = os.environ.get("PRIZEPICKS_API_KEY")
BASE = "https://prizepicksapi.com"
PATH = "/api/v1/projections" if API_KEY else "/api/v1/demo/projections"
HEADERS = {"Accept": "application/json"}
if API_KEY:
    HEADERS["Authorization"] = "Bearer " + API_KEY
    HEADERS["X-User-Request"] = "Read five NBA props for an integration check"


def projections(league="NBA", stat=None, max_pages=1):
    cursor = None
    seen_cursors = set()
    for page_number in range(max_pages):
        params = {"league": league, "limit": 5}
        if stat:
            params["stat"] = stat
        if cursor:
            params["cursor"] = cursor
        request = Request(BASE + PATH + "?" + urlencode(params), headers=HEADERS)
        try:
            with urlopen(request, timeout=20) as response:
                page = json.load(response)
        except HTTPError as error:
            detail = error.read().decode("utf-8", errors="replace")
            raise RuntimeError(f"HTTP {error.code}: {detail}") from None
        except URLError as error:
            raise RuntimeError(f"Request failed: {error.reason}") from None

        meta = page["meta"]
        print("Source:", meta["source_status"], "Observed:", meta["observed_at"])
        for projection in page["data"]:
            if API_KEY and projection.get("is_demo"):
                raise RuntimeError("Unexpected demo record in live response")
            yield projection

        cursor = meta.get("next_cursor")
        if not cursor:
            return
        if cursor in seen_cursors:
            raise RuntimeError("Repeated pagination cursor")
        seen_cursors.add(cursor)
        if page_number + 1 == max_pages:
            print("Partial board: more rows are available; increase max_pages deliberately.")
            return
        time.sleep(1.1)  # Pace serial page requests below the Free minute limit.


if __name__ == "__main__":
    print("Mode:", "authenticated observations" if API_KEY else "fictional demo")
    for item in projections():
        print(item["id"], item["player"]["name"], item["market"]["stat"], item["line"])
