"""Lineval API v1 quick start in Python (3.10 or later): the REST calls, then the stream with resume.

    pip install websockets
    BASE_URL=https://api.lineval.com API_KEY={API_KEY} python quickstart.py [seconds]

Without ``seconds`` the stream runs until you stop it. Set LINES and STREAM to products your
key includes.
"""
import asyncio
import json
import os
import random
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

import websockets
from websockets.exceptions import ConnectionClosed

BASE_URL = os.environ.get("BASE_URL", "https://api.lineval.com").rstrip("/")
API_KEY = os.environ["API_KEY"]
LINES = "live"                              # a product of lines: live, pregame or props
STREAM = ["live", "scores", "grading"]      # the products to follow on the stream
# Closes that reconnecting does not fix: change the request or the key first.
FATAL = {4400: "a parameter is not valid", 4401: "the key is missing, unknown or revoked",
         4403: "the key does not include one of the products"}
# A heartbeat comes every 15 s when nothing else does: this long without a message is a dead
# connection.
SILENCE_S = 45
# A connection that lasted this long was working: the back-off starts over.
STEADY_S = 60


class ApiError(Exception):
    pass


# ── REST ──────────────────────────────────────────────────────────────────────

def get(path):
    """GET a path of the API. Waits and retries on 429 and 503, raises on any other error."""
    for _ in range(5):
        request = urllib.request.Request(BASE_URL + path, headers={"Authorization": f"Bearer {API_KEY}"})
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                return json.load(response)
        except urllib.error.HTTPError as exc:
            if exc.code in (429, 503):
                time.sleep(int(exc.headers.get("Retry-After") or 5))
                continue
            try:
                error = json.loads(exc.read())["error"]
            except (ValueError, KeyError):
                error = {"code": None, "message": exc.reason, "requestId": None}
            raise ApiError(f"{exc.code} {error['code']}: {error['message']} (requestId {error['requestId']})")
    raise ApiError(f"{path}: still unavailable, try again later")


def rest():
    events = get(f"/v1/{LINES}/events?limit=5")["data"]
    print(f"{LINES}: {len(events)} events")
    if events:
        event = get(f"/v1/{LINES}/events/{events[0]['id']}")
        print(f"{event['id']} {event['name']}: {len(event['markets'])} markets")
        # The game's family: where it is offered, and where its scoresheet and verdicts are.
        family = get(f"/v1/events/{event['id']}")
        print("offered in:", ", ".join(p["product"] for p in family["products"]))
        if family["scoresheet"]:
            sheet = get(family["scoresheet"])
            print(f"scoresheet: {sheet['status']} {sheet['score']}, {sheet['confidence']}")
        for link in family["grading"]:
            grading = get(link["href"])
            print(f"grading of {link['product']}: {sum(len(m['selections']) for m in grading['markets'])} "
                  f"verdicts, {len(grading['held'])} held")
    # The latest confirmed scoresheets and verdicts of every game: to settle, use only these.
    sheets = get("/v1/scores?confidence=confirmed&limit=5")["data"]
    print(f"confirmed scoresheets: {len(sheets)}")
    gradings = get(f"/v1/{LINES}/grading?limit=5")["data"]
    print(f"{LINES} games graded: {len(gradings)}")


# ── the stream ────────────────────────────────────────────────────────────────

def apply(state, msg):
    """Keep what the stream says, per product: events with their markets, and the documents
    (scoresheets, verdicts, results) by game."""
    kind, data = msg["type"], msg["data"]
    if kind == "heartbeat":
        return
    product = state.setdefault(msg["product"], {"events": {}, "documents": {}})
    events = product["events"]
    if kind == "snapshot.begin":
        events.clear()
    elif kind == "snapshot":
        events[data["id"]] = {**data, "markets": {m["id"]: m for m in data["markets"]}}
    elif kind == "event.upsert":
        markets = events.get(data["id"], {}).get("markets", {})
        events[data["id"]] = {**data, "markets": markets}
    elif kind == "event.remove":
        events.pop(data["eventId"], None)
    elif kind == "market.upsert" and data["eventId"] in events:
        events[data["eventId"]]["markets"][data["id"]] = data
    elif kind == "market.remove" and data["eventId"] in events:
        events[data["eventId"]]["markets"].pop(data["marketId"], None)
    elif kind in ("scoresheet", "grading", "result"):
        # Each one replaces the last of its game (grading: of its game and product of lines).
        product["documents"][(data["eventId"], data.get("product"))] = data


def stream_url(since):
    query = {"products": ",".join(STREAM)}
    if since:
        query["since"] = ",".join(f"{p}:{seq}" for p, seq in since.items())
    return BASE_URL.replace("http", "ws", 1) + "/v1/stream?" + urllib.parse.urlencode(query, safe=",:")


async def follow(seconds=None):
    """Follow the stream; on a close that is not fatal, reconnect with ``since`` and lose nothing."""
    state, since = {}, {}           # since: the last seq applied per product, once its snapshot ended
    deadline = time.monotonic() + seconds if seconds else float("inf")
    delay = 1.0
    while time.monotonic() < deadline:
        url = stream_url(since)
        print(f"connecting: {url[url.index('/v1/'):]}")
        opened = time.monotonic()
        try:
            async with websockets.connect(url, additional_headers={"Authorization": f"Bearer {API_KEY}"}) as ws:
                in_snapshot = set()
                while True:
                    wait = min(SILENCE_S, deadline - time.monotonic())
                    if wait <= 0:
                        break
                    msg = json.loads(await asyncio.wait_for(ws.recv(), wait))
                    kind, product = msg["type"], msg["product"]
                    apply(state, msg)
                    # A snapshot is whole only at its end: cut off before it, ask for a new one.
                    if kind == "snapshot.begin":
                        in_snapshot.add(product)
                        since.pop(product, None)
                    elif kind == "snapshot.end":
                        in_snapshot.discard(product)
                        since[product] = msg["data"]["since"]
                        print(f"{product}: snapshot, {len(state[product]['events'])} events")
                    elif msg["seq"] is not None and product not in in_snapshot:
                        since[product] = msg["seq"]
                    if kind not in ("snapshot.begin", "snapshot", "snapshot.end", "heartbeat"):
                        print(f"{product}: {kind}", msg["data"].get("id") or msg["data"].get("eventId") or "")
        except asyncio.TimeoutError:
            if time.monotonic() < deadline:
                print(f"no message in {SILENCE_S} s: reconnecting")
        except ConnectionClosed as exc:
            code, reason = (exc.rcvd.code, exc.rcvd.reason) if exc.rcvd else (1006, "connection lost")
            if code in FATAL:
                raise ApiError(f"stream closed {code}: {reason or FATAL[code]}")
            print(f"closed {code} ({reason}): reconnecting")
        except OSError as exc:
            print(f"cannot connect ({exc}): retrying")
        if time.monotonic() - opened >= STEADY_S:
            delay = 1.0
        if time.monotonic() < deadline:
            await asyncio.sleep(delay + random.random())
            delay = min(delay * 2, 30.0)
    return state


if __name__ == "__main__":
    try:
        rest()
        asyncio.run(follow(float(sys.argv[1]) if len(sys.argv) > 1 else None))
    except ApiError as exc:
        sys.exit(f"error: {exc}")
