"""Python client for the finals market API (service/API.md), for participant bots.

    from client import Client              # from the root of this repository
    from muniquant_client import Client    # this file alone, downloaded from <server>/api/client.py

    with Client("http://127.0.0.1:8000", api_key="...") as c:
        c.wait_for_start()
        print(c.market()["mid"], c.account()["position"])
        c.buy(2)                                   # market order, 2 lots
        for msg in c.stream():                     # live feed: snapshot, then one tick per step
            if msg["type"] == "finished":
                break

What it does for you, and nothing more (rulebook Section 4: no strategy here):
- sends the X-API-Key header on every call;
- gives every order a request_id, so a retry after a timeout or a lost answer is answered with the first result
  (also when the retry arrives while the first request is still being processed);
- waits and retries when the server answers HTTP 429 (over the order-action limit: nothing changed, open orders stay);
- turns error answers into exceptions with the server's message (Rejected for 422, RateLimited for 429, ...);
- reconnects the WebSocket feed with since=<seq> and fills the gap from GET /ticks, so a bot misses no tick.

Needs httpx; stream() also needs websockets (13 or later). Both are in requirements.txt.
"""
from __future__ import annotations

import json
import time
import uuid
from typing import Any, Callable, Iterator

import httpx

LOT_T = 25   # tonnes per lot

__all__ = ["Client", "APIError", "Unauthorized", "NotFound", "Conflict", "Rejected", "RateLimited"]


class APIError(Exception):
    """The server refused a call. `status` is the HTTP status, `detail` the server's message."""

    def __init__(self, status: int, detail: Any, method: str = "", path: str = ""):
        self.status, self.detail, self.method, self.path = status, detail, method, path
        super().__init__(f"{method} {path}: HTTP {status}: {detail}".strip())


class Unauthorized(APIError):
    """401: missing or unknown API key."""


class NotFound(APIError):
    """404: e.g. an order id that is not yours or no longer resting."""


class Conflict(APIError):
    """409: not possible in this state of the round (e.g. candles without --subticks)."""


class Rejected(APIError):
    """422: the order or setting breaks a rule (lot size, position limit, loss limit, margin, ...)."""


class RateLimited(APIError):
    """429: still over the order-action limit after all retries. Nothing changed; open orders stay."""


_ERRORS = {401: Unauthorized, 404: NotFound, 409: Conflict, 422: Rejected, 429: RateLimited}


class Client:
    """One participant's connection to the market.

    url: the server, e.g. http://127.0.0.1:8000 (from the organiser).
    api_key: your key (`X-API-Key`); a one-time sign-in code can be swapped for it with `Client.sign_in`.
    retries: how often a call is repeated after HTTP 429 or a network error (only where repeating is safe).
    backoff: the first wait in seconds; it doubles on every retry.
    http, connect, sleep: for tests (an httpx.Client such as FastAPI's TestClient, a WebSocket opener, a sleep).
    """

    def __init__(self, url: str, api_key: str, *, timeout: float = 5.0, retries: int = 3, backoff: float = 0.25,
                 http: httpx.Client | None = None, connect: Callable[[str], Any] | None = None,
                 sleep: Callable[[float], None] = time.sleep):
        self.url = url.rstrip("/")
        self.api_key = api_key
        self.retries, self.backoff, self.sleep = retries, backoff, sleep
        self._own_http = http is None
        self.http = http if http is not None else httpx.Client(base_url=self.url, timeout=timeout)
        self._connect = connect or self._websocket

    # ---- sign-in ---------------------------------------------------------------------------------------------------
    @staticmethod
    def sign_in(url: str, code: str, *, http: httpx.Client | None = None, **kwargs) -> "Client":
        """Swap the code of a personal sign-in link (`.../#c=<code>`) for an API key. Each code works once."""
        h = http if http is not None else httpx.Client(base_url=url.rstrip("/"), timeout=kwargs.get("timeout", 5.0))
        try:
            r = h.post("/session", json={"code": code})
        finally:
            if http is None:
                h.close()
        if r.status_code != 200:
            raise _error(r, "POST", "/session")
        body = r.json()
        if body.get("role") != "player":
            raise APIError(r.status_code, "this is an organiser link, not a player link", "POST", "/session")
        return Client(url, body["api_key"], http=http, **kwargs)

    # ---- low level ---------------------------------------------------------------------------------------------------
    def request(self, method: str, path: str, *, json_body: Any = None, params: dict | None = None,
                retry: bool = True) -> Any:
        """One API call. Retries after HTTP 429 always (the server changed nothing) and after a network error only
        when `retry` is true (reads, and orders with a request_id)."""
        wait = self.backoff
        for attempt in range(self.retries + 1):
            last = attempt == self.retries
            try:
                r = self.http.request(method, path, json=json_body, params=params,
                                      headers={"X-API-Key": self.api_key})
            except httpx.TransportError:
                if not retry or last:
                    raise
                self.sleep(wait)
                wait *= 2
                continue
            if r.status_code == 429 and not last:
                self.sleep(wait)
                wait *= 2
                continue
            if r.status_code >= 400:
                raise _error(r, method, path)
            return r.json()
        raise AssertionError("unreachable")

    # ---- reading the market -----------------------------------------------------------------------------------------
    def market(self) -> dict:
        """Best bid/ask, last, mid, depth, step, day, state, the last 50 headlines, limits."""
        return self.request("GET", "/market")

    def account(self) -> dict:
        """Your position, cash, equity, PnL, open orders, fills, stop, limits."""
        return self.request("GET", "/account")

    def news(self) -> list[dict]:
        """Every headline of the round so far, oldest first."""
        return self.request("GET", "/news")

    def event_types(self) -> list[dict]:
        """The news booklet: one entry per event type, no numbers."""
        return self.request("GET", "/event-types")

    def leaderboard(self) -> list[dict]:
        return self.request("GET", "/leaderboard")

    def season(self) -> dict:
        """Quarter, break countdown and year standings (`{"enabled": false}` without season mode)."""
        return self.request("GET", "/season")

    def ticks(self, since: int = -1, round_id: str | None = None) -> dict:
        """The compact ticks after `since` (at most the last 2,000). `reset` = reload a full snapshot."""
        params: dict = {"since": since}
        if round_id is not None:
            params["round"] = round_id
        return self.request("GET", "/ticks", params=params)

    def candles(self, tf: str = "1m", since: int | None = None, limit: int = 2000) -> dict:
        """Server-side candles: tf = tick | 1s | 5s | 1m | 1h. Needs a server with --subticks (else Conflict)."""
        params: dict = {"tf": tf, "limit": limit}
        if since is not None:
            params["since"] = since
        return self.request("GET", "/candles", params=params)

    def position(self, market: str = "lme") -> int:
        """Your lots in one market (positive = long). With a bot key (qualifier "My bots"): this bot's own lots, so
        several bots on one account each trade their own position (set_exposure, target_position)."""
        a = self.account()
        if "bot" in a and market == "lme":
            return a["bot"]["position"]
        return a["position"] if market == "lme" else a["markets"][market]["position"]

    def wait_for_start(self, poll: float = 0.5, timeout: float | None = None) -> dict:
        """Poll /market until the round runs (or is over) and return that market view. In a season, the break between
        two quarters also counts as waiting: it returns when the next quarter runs, or once the last one is over."""
        end = None if timeout is None else time.monotonic() + timeout
        while True:
            m = self.market()
            if m.get("state") == "running":
                return m
            if (m.get("state") == "finished" or m.get("finished")) and not self.season().get("waiting"):
                return m
            if end is not None and time.monotonic() >= end:
                raise TimeoutError("the round has not started")
            self.sleep(poll)

    # ---- trading -----------------------------------------------------------------------------------------------------
    def order(self, side: str, qty: int, price: float | None = None, *, market: str = "lme",
              request_id: str | None = None) -> dict:
        """Place one order: market order without `price`, limit order with it. Returns order_id, filled, resting,
        fills. A request_id is made for you; pass your own to retry a call yourself (the server answers a known id with
        the first result)."""
        if side not in ("buy", "sell"):
            raise ValueError("side must be 'buy' or 'sell'")
        body: dict = {"side": side, "qty": qty, "type": "market" if price is None else "limit",
                      "request_id": request_id or str(uuid.uuid4()), "market": market}
        if price is not None:
            body["price"] = price
        return self.request("POST", "/orders", json_body=body)

    def buy(self, qty: int, price: float | None = None, **kwargs) -> dict:
        return self.order("buy", qty, price, **kwargs)

    def sell(self, qty: int, price: float | None = None, **kwargs) -> dict:
        return self.order("sell", qty, price, **kwargs)

    def cancel(self, order_id: int) -> dict:
        """Cancel one of your resting orders (NotFound if it is not resting any more)."""
        return self.request("DELETE", f"/orders/{order_id}", retry=False)

    def cancel_all(self, market: str = "lme") -> dict:
        """All your resting orders in one market, as one order action."""
        return self.request("POST", "/orders/cancel-all", json_body={"market": market}, retry=False)

    def close_position(self, market: str = "lme") -> dict:
        """Cancel your resting orders in one market and trade back to 0 at market, as one order action."""
        return self.request("POST", "/position/close", json_body={"market": market}, retry=False)

    def max_lots(self, fraction: float = 1.0, side: str = "buy") -> int:
        """Lots worth at most `fraction` of your equity at the current buy (side="buy") or sell price, never more
        than the position limit. 1.0 = 100 % of your capital (the most a qualifier round allows)."""
        if not 0 <= fraction <= 1:
            raise ValueError("fraction must be between 0 and 1")
        a, m = self.account(), self.market()
        price = m.get("ask" if side == "buy" else "bid") or m.get("mid")
        if not price:
            return 0
        return max(0, min(int(fraction * a["equity"] // (price * LOT_T)), a["position_limit"]))

    def target_position(self, lots: int, market: str = "lme") -> int:
        """Trade at market until your position is `lots` (negative = short), in clips of the round's max lots per
        order. Returns the position afterwards (it stops early if the server refuses an order, e.g. at a limit)."""
        a = self.account()
        pos, clip = self.position(market), a["max_clip"]
        while pos != lots:
            qty = min(abs(lots - pos), clip)
            try:
                self.order("buy" if lots > pos else "sell", qty, market=market)
            except Rejected:
                break
            pos = self.position(market)
        return pos

    def set_exposure(self, fraction: float) -> int:
        """Hold `fraction` of your capital: +1.0 = long with 100 %, -1.0 = short with 100 %, 0 = flat. Works out
        the lots from your equity and the current price. Returns the position afterwards."""
        if not -1 <= fraction <= 1:
            raise ValueError("fraction must be between -1 and 1")
        lots = self.max_lots(abs(fraction), "buy" if fraction > 0 else "sell") if fraction else 0
        return self.target_position(lots if fraction >= 0 else -lots)

    def download_history(self, folder: str = "qualifier_history") -> dict[str, str]:
        """Qualifier rounds: save the history (prices per hour and per day, every news item) as CSV files into
        `folder` and return their paths. Read them with pandas, e.g. pd.read_csv(paths["prices_hourly.csv"])."""
        import os
        os.makedirs(folder, exist_ok=True)
        out = {}
        for name in ("prices_hourly.csv", "prices_daily.csv", "news.csv"):
            r = self.http.get(f"/data/history/{name}", timeout=60)
            if r.status_code != 200:
                raise _error(r, "GET", f"/data/history/{name}")
            path = os.path.join(folder, name)
            with open(path, "wb") as f:
                f.write(r.content)
            out[name] = path
        return out

    def set_stop(self, price: float) -> dict:
        """Stop loss on the valuation mark: the whole position is closed at market when the mark reaches `price`."""
        return self.request("POST", "/stop", json_body={"price": price}, retry=False)

    def clear_stop(self) -> dict:
        return self.request("DELETE", "/stop", retry=False)

    def set_leverage(self, leverage: float) -> dict:
        """1 up to the server's --max-leverage: whole numbers, and 1.5, 2.5 when the server allows 0.5x steps
        (--leverage-step 0.5). Also before the round starts. The server checks the value (Rejected otherwise) and
        refuses it on a server without leverage."""
        return self.request("POST", "/leverage", json_body={"leverage": leverage}, retry=False)

    def set_cancel_on_disconnect(self, enabled: bool) -> dict:
        """Before the round starts only. Switch it off for a REST-only bot that rests orders and polls less often
        than every 10 s; stream() keeps you connected otherwise."""
        return self.request("POST", "/cancel-on-disconnect", json_body={"enabled": enabled}, retry=False)

    # ---- live feed ---------------------------------------------------------------------------------------------------
    def stream(self, *, reconnect: bool = True, max_reconnects: int | None = None, auth: bool = True) -> Iterator[dict]:
        """Live messages from /ws/market: a `snapshot` first, then `tick` (one per step), `sub` (with --subticks),
        `status`, `season` and `finished`. `max_reconnects` = failed reconnects in a row before it gives up.

        After a dropped connection it reconnects with since=<seq>. The server then sends a short `hello`; the ticks
        missed in between are fetched from /ticks and yielded in order as compact ticks with `"recovered": True`
        (step, day, mid, volume, official_mark, news, state "running"; no book: the next live tick has it; the
        hello before them has the state now). If the gap cannot be
        filled, a new `snapshot` comes instead: start your state over from it. Ticks are never yielded twice.
        """
        seq, round_id, last_tick, drops = None, None, None, 0
        while True:
            query = "" if seq is None else f"?since={seq}&round={round_id}"
            try:
                ws = self._connect("/ws/market" + query)
            except Exception:
                drops += 1
                if not reconnect or (max_reconnects is not None and drops > max_reconnects):
                    raise
                self.sleep(min(self.backoff * 2 ** min(drops, 5), 5.0))
                continue
            try:
                if auth:
                    ws.send(json.dumps({"type": "auth", "key": self.api_key}))
                while True:
                    msg = json.loads(ws.recv())
                    drops = 0                         # max_reconnects counts drops in a row, not over the session
                    kind = msg.get("type")
                    if kind == "snapshot":
                        last_tick = msg.get("seq")
                    elif kind == "hello" and seq is not None:
                        yield msg
                        gap = self.ticks(seq, round_id)
                        if gap["reset"]:              # gap no longer fillable: get a fresh snapshot
                            raise _Resync()
                        for t in gap["ticks"]:
                            if last_tick is None or t["seq"] > last_tick:
                                last_tick = t["seq"]
                                yield {"type": "tick", "recovered": True, "round": gap["round"], "state": "running", **t}
                        seq, round_id = gap["seq"], gap["round"]
                        continue
                    elif kind == "tick":
                        if last_tick is not None and msg.get("seq", 0) <= last_tick and msg.get("round") == round_id:
                            continue
                        last_tick = msg.get("seq")
                    seq, round_id = msg.get("seq", seq), msg.get("round", round_id)
                    yield msg
            except _Resync:
                seq, round_id, last_tick = None, None, None
            except APIError as exc:
                if exc.status < 500:                  # refused (e.g. 401 on /ticks): reconnecting will not help
                    raise
                drops += 1                            # 5xx: the server is restarting; treat it like a drop
                if not reconnect or (max_reconnects is not None and drops > max_reconnects):
                    raise
                self.sleep(min(self.backoff * 2 ** min(drops, 5), 5.0))
            except json.JSONDecodeError:
                raise                                 # not a connection problem: show it instead of reconnecting
            except Exception:
                drops += 1
                if not reconnect or (max_reconnects is not None and drops > max_reconnects):
                    raise
                self.sleep(min(self.backoff * 2 ** min(drops, 5), 5.0))
            finally:
                _close(ws)

    def _websocket(self, path: str):
        from websockets.sync.client import connect   # imported here so REST-only bots do not need it

        base = "wss://" + self.url[8:] if self.url.startswith("https://") else "ws://" + self.url.split("://", 1)[-1]
        return connect(base + path)

    # ---- housekeeping ------------------------------------------------------------------------------------------------
    def close(self) -> None:
        if self._own_http:
            self.http.close()

    def __enter__(self) -> "Client":
        return self

    def __exit__(self, *exc) -> None:
        self.close()


class _Resync(Exception):
    """Internal: reconnect without since, to get a full snapshot."""


def _error(r: httpx.Response, method: str, path: str) -> APIError:
    try:
        detail = r.json().get("detail", r.text)
    except ValueError:
        detail = r.text
    return _ERRORS.get(r.status_code, APIError)(r.status_code, detail, method, path)


def _close(ws) -> None:
    try:
        ws.close()
    except Exception:
        pass
