#!/usr/bin/env python3
"""Print one player's retained ESPN game log, or list athletes when no id is given.

Independent service, not affiliated with or endorsed by DraftKings. No wagering.
Run: python3 player-game-log.py --sport NBA --season 2027 --athlete-id 1966 --stat points --max-pages 3
Seasons: NFL uses its starting year; NBA and NHL use their ending year.
Retained samples are limited and do not establish a full season. ESPN ids are not DraftKings ids.
"""
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 stat_value(row, key):
    for stat in row["data"].get("stats", []):
        if stat["key"] == key and stat.get("scope") == "game":
            return stat.get("numeric") if stat.get("numeric") is not None else stat.get("display")
    return None


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--sport", required=True, choices=["NBA", "NFL", "NHL"])
    parser.add_argument("--season", required=True, type=int)
    parser.add_argument("--athlete-id")
    parser.add_argument("--stat", help="ESPN stat key such as points, receivingYards or shotsTotal")
    parser.add_argument("--max-pages", type=int, default=3)
    args = parser.parse_args()
    client = Client(max_requests=args.max_pages)
    rows, after = [], None
    for _ in range(args.max_pages):
        page = client.get("/api/v1/stats/player-games", sport=args.sport, season=args.season, athlete_id=args.athlete_id, limit=200, after=after)
        rows.extend(page["data"])
        after = page["pagination"]["next"]
        if not after:
            break
    if not rows:
        sys.exit("No stored rows match. A valid season does not establish availability. Check /status.")
    if not args.athlete_id:
        athletes = sorted({(r["data"]["name"], r["data"]["athlete_id"]) for r in rows})
        for name, athlete_id in athletes:
            print(f"{athlete_id:>12}  {name}")
        print(f"{len(athletes)} athletes on {client.requests} pages. More may exist. Rerun with --athlete-id.")
        return
    rows.sort(key=lambda r: r.get("game", {}).get("starts_at", ""))
    for row in rows:
        game = row.get("game", {})
        value = stat_value(row, args.stat) if args.stat else [s["key"] for s in row["data"].get("stats", [])]
        print(f"{game.get('starts_at', '')[:10]} event={game.get('event_id')} state={game.get('state')} {row['data'].get('category')} {args.stat or 'keys'}={value}")
    print(f"{len(rows)} retained rows. Do not treat this as a complete log.")


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