#!/usr/bin/env python3
"""Print recorded Pick6 rows for one sport and stat, skipping stale and paused rows.

Independent service, not affiliated with or endorsed by DraftKings. No wagering.
Run: python3 pick6-board.py --sport NHL --stat "Shots on Goal" --limit 25 --max-pages 2
Spends at most --max-pages requests. A row is a market, not a unique athlete.
"""
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", required=True)
    parser.add_argument("--stat")
    parser.add_argument("--limit", type=int, default=25)
    parser.add_argument("--max-pages", type=int, default=2)
    parser.add_argument("--include-stale", action="store_true")
    args = parser.parse_args()
    client = Client(max_requests=args.max_pages)
    offset, shown, skipped = 0, 0, 0
    for _ in range(args.max_pages):
        page = client.get("/api/v1/pick6/projections", sport=args.sport, stat=args.stat, limit=args.limit, offset=offset)
        for row in page["data"]:
            if row.get("is_paused") or (row["stale"] and not args.include_stale):
                skipped += 1
                continue
            shown += 1
            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:<28} {row.get('stat'):<22} {row.get('target_value'):>7} {sides:<24} age={row['age_seconds']}s")
        if not page["pagination"]["has_more"]:
            break
        offset += args.limit
    print(f"{shown} rows shown, {skipped} stale or paused rows skipped, {client.requests} requests used.")
    if shown == 0:
        print("No fresh rows. Check https://draftkingsapi.com/status, or pass --include-stale to read retained rows.")


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