"""T21 Python client: one credential, short-lived access tokens handled for you.

A single file using only the Python standard library (3.9+). Download it from
the T21 Platform next to your code (GET /sdk/python/t21.py), then::

    from t21 import T21

    t21 = T21("t21c....")  # or set the T21_CREDENTIAL environment variable
    print(t21.stats()["data"])

The credential is exchanged at the Platform for a 5-minute access token. The
client caches it, renews it before it expires, and retries once if T21 reports
the token expired. Every call returns T21's response envelope; the payload is
under ``["data"]`` and ``["request_id"]`` identifies the call.

Keep the credential secret out of source control. It never appears in this
client's ``repr``, errors or messages.
"""

from __future__ import annotations

import json
import os
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from typing import Any, Callable, Iterable, Optional

__version__ = "0.1.0"
__all__ = ["T21", "T21Error", "ROUTES", "__version__"]

PLATFORM_URL = "https://platform.t21.one"
API_URL = "https://api.t21.one"

#: Seconds before expiry at which a cached token is renewed.
RENEW_MARGIN = 30.0
#: Refusals that a fresh token can fix: renew once and retry.
RENEWABLE = frozenset({"token_expired", "token_not_yet_valid"})
#: Refusals about revocation state that usually clear within a second: retry once.
TRANSIENT = frozenset({"snapshot_not_yet_valid", "snapshot_missing", "snapshot_expired"})

#: The routes the helper methods call. Each is reachable with a Platform token,
#: which the Platform's tests check against its scope catalogue.
ROUTES = {
    "stats": "/v1/data/stats",
    "securities": "/v1/data/securities",
    "security": "/v1/data/securities/{symbol}",
    "prices": "/v1/data/prices",
    "price_history": "/v1/data/prices/{symbol}",
    "trades": "/v1/market/trades",
    "candles": "/v1/market/candles/{symbol}",
    "listed_companies": "/v1/market/listed-companies",
    "dividends": "/v1/market/dividends",
    "disclosures": "/v1/market/disclosures",
    "ownership": "/v1/intelligence/{symbol}/ownership",
    "knowledge_graph": "/v1/intelligence/{symbol}/knowledge-graph",
    "financial_statements": "/v1/intelligence/{symbol}/financial-statements",
}


class T21Error(Exception):
    """A refusal or failure, with the contract error code when T21 sent one.

    ``status`` is the HTTP status (0 when no response arrived), ``code`` the
    machine-readable reason (for example ``scope_missing`` or
    ``credential_invalid``), and ``request_id`` the id to quote in a report.
    """

    def __init__(self, status: int, code: str, message: str = "", request_id: str = "") -> None:
        self.status = status
        self.code = code
        self.message = message
        self.request_id = request_id
        text = f"{status} {code}"
        if message:
            text += f": {message}"
        if request_id:
            text += f" (request {request_id})"
        super().__init__(text)


def _error_from(status: int, raw: bytes, headers: Any) -> T21Error:
    """Read the error shapes T21 and the Platform use into one exception."""
    code, message = "http_error", ""
    try:
        body = json.loads(raw.decode("utf-8")) if raw else None
    except (ValueError, UnicodeError):
        body = None
    if isinstance(body, dict):
        error, detail = body.get("error"), body.get("detail")
        if isinstance(error, dict) and isinstance(error.get("code"), str):
            code, message = error["code"], str(error.get("message") or "")
        elif isinstance(detail, dict) and isinstance(detail.get("code"), str):
            code, message = detail["code"], str(detail.get("message") or "")
        elif isinstance(body.get("code"), str):
            # Problem documents, e.g. 502 UPSTREAM_UNREACHABLE.
            code, message = body["code"], str(body.get("detail") or "")
        elif isinstance(detail, str):
            message = detail
    request_id = ""
    if headers is not None:
        request_id = str(headers.get("X-Request-Id") or "")
    if isinstance(body, dict) and not request_id:
        request_id = str(body.get("request_id") or "")
    return T21Error(status, code, message, request_id)


class T21:
    """A client for the hosted T21 API, authenticated by a Platform credential."""

    def __init__(
        self,
        credential: Optional[str] = None,
        *,
        scopes: Optional[Iterable[str]] = None,
        api_url: Optional[str] = None,
        platform_url: Optional[str] = None,
        timeout: float = 30.0,
        _urlopen: Optional[Callable[..., Any]] = None,
        _clock: Optional[Callable[[], float]] = None,
        _sleep: Optional[Callable[[float], None]] = None,
    ) -> None:
        secret = (credential if credential is not None else os.environ.get("T21_CREDENTIAL", "")).strip()
        if not (secret.startswith("t21c.") and secret.count(".") == 2):
            raise ValueError(
                "a T21 credential secret (it starts with 't21c.') is required: "
                "pass it to T21(...) or set T21_CREDENTIAL"
            )
        self._secret = secret
        self._requested_scopes = sorted(set(scopes)) if scopes is not None else None
        self.api_url = (api_url or os.environ.get("T21_API_URL") or API_URL).rstrip("/")
        self.platform_url = (platform_url or os.environ.get("T21_PLATFORM_URL") or PLATFORM_URL).rstrip("/")
        self.timeout = float(timeout)
        self._urlopen = _urlopen or urllib.request.urlopen
        self._clock = _clock or time.monotonic
        self._sleep = _sleep or time.sleep
        self._lock = threading.Lock()
        self._token: Optional[str] = None
        self._expires_at = 0.0
        #: Scopes granted to the current access token (empty until the first call).
        self.scopes: tuple[str, ...] = ()

    def __repr__(self) -> str:
        return f"T21(api_url={self.api_url!r}, platform_url={self.platform_url!r})"

    # -- transport ---------------------------------------------------------

    def _send(self, method: str, url: str, *, body: Any = None, headers: Optional[dict] = None) -> Any:
        data = None if body is None else json.dumps(body).encode("utf-8")
        merged = {"Accept": "application/json", "User-Agent": f"t21-python/{__version__}"}
        if data is not None:
            merged["Content-Type"] = "application/json"
        merged.update(headers or {})
        request = urllib.request.Request(url, data=data, method=method, headers=merged)
        try:
            with self._urlopen(request, timeout=self.timeout) as response:
                raw = response.read()
        except urllib.error.HTTPError as exc:
            try:
                raw = exc.read()
            except OSError:
                raw = b""
            raise _error_from(exc.code, raw, exc.headers) from None
        except urllib.error.URLError as exc:
            raise T21Error(0, "connection_failed", str(exc.reason)) from None
        except OSError as exc:  # timeouts and resets outside URLError
            raise T21Error(0, "connection_failed", type(exc).__name__) from None
        try:
            return json.loads(raw.decode("utf-8"))
        except (ValueError, UnicodeError):
            raise T21Error(200, "invalid_response", "the response is not JSON") from None

    def _access_token(self, *, renew: bool = False) -> str:
        with self._lock:
            if not renew and self._token and self._clock() < self._expires_at - RENEW_MARGIN:
                return self._token
            request: dict[str, Any] = {"credential_secret": self._secret}
            if self._requested_scopes is not None:
                request["scopes"] = self._requested_scopes
            issued = self._send("POST", self.platform_url + "/v1/token", body=request)
            token = issued.get("access_token") if isinstance(issued, dict) else None
            if not isinstance(token, str) or not token.startswith("v4.public."):
                raise T21Error(200, "invalid_response", "the Platform returned no access token")
            self._token = token
            self._expires_at = self._clock() + float(issued.get("expires_in") or 300)
            self.scopes = tuple(issued.get("scopes") or ())
            return token

    # -- requests ----------------------------------------------------------

    def get(self, path: str, **params: Any) -> Any:
        """GET a T21 route, for example ``t21.get("/v1/market/trades", symbol="APU")``.

        Parameters whose value is ``None`` are left out. Returns the response
        envelope; raises :class:`T21Error` on a refusal.
        """
        if not path.startswith("/"):
            raise ValueError("path must start with '/', for example '/v1/data/stats'")
        query = {key: value for key, value in params.items() if value is not None}
        url = self.api_url + path
        if query:
            url += "?" + urllib.parse.urlencode(query, doseq=True)
        renew = renewed = waited = False
        while True:
            token = self._access_token(renew=renew)
            renew = False
            try:
                return self._send("GET", url, headers={"Authorization": "Bearer " + token})
            except T21Error as exc:
                if exc.code in RENEWABLE and not renewed:
                    renewed = renew = True
                    continue
                if exc.code in TRANSIENT and not waited:
                    waited = True
                    self._sleep(1.0)
                    continue
                raise

    def _route(self, name: str, **path_params: str) -> str:
        quoted = {key: urllib.parse.quote(str(value), safe="") for key, value in path_params.items()}
        return ROUTES[name].format(**quoted)

    # -- helpers -----------------------------------------------------------
    # Thin names for common routes; every keyword is passed through as a query
    # parameter, so anything a route accepts can be used without a new release.

    def stats(self, **params: Any) -> Any:
        """Coverage of the stored market data, including the newest session."""
        return self.get(self._route("stats"), **params)

    def securities(self, **params: Any) -> Any:
        return self.get(self._route("securities"), **params)

    def security(self, symbol: str, **params: Any) -> Any:
        return self.get(self._route("security", symbol=symbol), **params)

    def prices(self, symbol: Optional[str] = None, **params: Any) -> Any:
        """Latest prices across the market, or one symbol's price history."""
        if symbol:
            return self.get(self._route("price_history", symbol=symbol), **params)
        return self.get(self._route("prices"), **params)

    def trades(self, **params: Any) -> Any:
        return self.get(self._route("trades"), **params)

    def candles(self, symbol: str, **params: Any) -> Any:
        return self.get(self._route("candles", symbol=symbol), **params)

    def listed_companies(self, **params: Any) -> Any:
        return self.get(self._route("listed_companies"), **params)

    def dividends(self, **params: Any) -> Any:
        return self.get(self._route("dividends"), **params)

    def disclosures(self, **params: Any) -> Any:
        return self.get(self._route("disclosures"), **params)

    def ownership(self, symbol: str, **params: Any) -> Any:
        return self.get(self._route("ownership", symbol=symbol), **params)

    def knowledge_graph(self, symbol: str, **params: Any) -> Any:
        """The issuer as one connected object: holders, people, security, statements, events."""
        return self.get(self._route("knowledge_graph", symbol=symbol), **params)

    def financial_statements(self, symbol: str, **params: Any) -> Any:
        return self.get(self._route("financial_statements", symbol=symbol), **params)
