#!/usr/bin/env python3
"""First calls to the DraftKings API: one Pick6 page and one sportsbook page.

Independent service, not affiliated with or endorsed by DraftKings. No wagering.
Run: python3 draftkings-quickstart.py --sport NBA --limit 5
Spends at most 2 requests. Python 3.9+, standard library only.
"""
import argparse
import hashlib
import json
import os
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen

API_KEY = os.environ.get("DRAFTKINGS_API_KEY")
BASE = os.environ.get("DRAFTKINGS_API_BASE", "https://draftkingsapi.com").rstrip("/")
CACHE_DIR = Path(os.environ.get("DRAFTKINGS_CACHE_DIR", ".draftkings-cache"))
# Collection targets five minutes. Polling faster spends quota without newer data.
CACHE_TTL_SECONDS = 300


class ApiError(Exception):
    def __init__(self, status, message):
        super().__init__(f"HTTP {status}: {message}")
        self.status = status


class Client:
    """Bounded client: a request budget, a timeout, a file cache and limited retries."""

    def __init__(self, max_requests, use_cache=True):
        if not API_KEY:
            sys.exit("Set DRAFTKINGS_API_KEY in your environment. Create a key at https://draftkingsapi.com/dashboard")
        self.max_requests = max_requests
        self.requests = 0
        self.use_cache = use_cache

    def get(self, path, **params):
        query = {k: v for k, v in params.items() if v is not None}
        url = f"{BASE}{path}?{urlencode(query)}" if query else f"{BASE}{path}"
        cached = self._read_cache(url)
        if cached is not None:
            return cached
        body = self._fetch(url)
        self._write_cache(url, body)
        return body

    def _fetch(self, url):
        for attempt in range(3):
            if self.requests >= self.max_requests:
                raise ApiError(0, f"Local budget of {self.max_requests} requests reached. Raise it deliberately.")
            self.requests += 1
            request = Request(url, headers={"Authorization": f"Bearer {API_KEY}", "Accept": "application/json"})
            try:
                with urlopen(request, timeout=20) as response:
                    return json.load(response)
            except HTTPError as error:
                message = _error_message(error)
                can_retry = self.requests < self.max_requests
                if error.code == 429 and attempt == 0 and can_retry:
                    # Minute limits reset at the next UTC minute. A second 429 usually means the monthly allowance.
                    time.sleep(61 - datetime.now(timezone.utc).second)
                    continue
                if error.code >= 500 and attempt < 2 and can_retry:
                    time.sleep(2 ** attempt)
                    continue
                raise ApiError(error.code, message) from None
            except (URLError, TimeoutError) as error:
                if attempt < 2 and self.requests < self.max_requests:
                    time.sleep(2 ** attempt)
                    continue
                raise ApiError(0, f"Network failure: {error}") from None
        raise ApiError(429, "Account request limit reached. Check the allowance in your dashboard.")

    def _cache_path(self, url):
        return CACHE_DIR / (hashlib.sha256(url.encode()).hexdigest() + ".json")

    def _read_cache(self, url):
        path = self._cache_path(url)
        if not self.use_cache or not path.exists() or time.time() - path.stat().st_mtime > CACHE_TTL_SECONDS:
            return None
        return json.loads(path.read_text())

    def _write_cache(self, url, body):
        if self.use_cache:
            CACHE_DIR.mkdir(exist_ok=True)
            self._cache_path(url).write_text(json.dumps(body))


def _error_message(error):
    try:
        return json.load(error)["error"]["message"]
    except Exception:
        return error.reason


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--sport", default="NBA")
    parser.add_argument("--limit", type=int, default=5)
    args = parser.parse_args()
    client = Client(max_requests=2, use_cache=False)

    page = client.get("/api/v1/pick6/projections", sport=args.sport, limit=args.limit)
    print(f"Pick6 rows: {len(page['data'])}, has_more={page['pagination']['has_more']}")
    for row in page["data"]:
        name = (row.get("entities") or [{}])[0].get("full_name", "unknown")
        sides = ", ".join(f"{s.get('side')} {s.get('formatted_standings_multiplier')}" for s in row.get("selections", []))
        print(f"  {name} | {row.get('stat')} {row.get('target_value')} | {sides} | age {row['age_seconds']}s stale={row['stale']}")

    page = client.get("/api/v1/odds", sport=args.sport, limit=args.limit)
    print(f"Sportsbook rows: {len(page['data'])}")
    for row in page["data"]:
        print(f"  {row['event_id']} | {row['market']} {row['side']} line={row['line']} american={row['american']} | {row['event_status']} stale={row['stale']}")

    print("Standings multipliers are not odds. observed_at is a capture clock, not a venue clock.")


if __name__ == "__main__":
    try:
        main()
    except ApiError as error:
        sys.exit(str(error))
