"""ChoicePaid API client for Python 3.8+. Standard library only.

    from choicepaid import ChoicePaid
    cp = ChoicePaid(os.environ["CHOICEPAID_KEY"])
    for inv in cp.invoices.list_all(status="submitted"):
        print(inv["number"], inv["total_cents"])

Writes get an Idempotency-Key automatically, so the client can retry them safely after a timeout, a 429 or a
server error without creating anything twice.
"""

from __future__ import annotations

import hashlib
import hmac
import json
import random
import re
import time
import uuid
from typing import Any, Dict, Iterator, Optional
from urllib import error, parse, request

__version__ = "1.0.0"
__all__ = ["ChoicePaid", "ChoicePaidError", "verify_webhook"]

DEFAULT_BASE_URL = "https://www.choicepaid.com/api/v1"


class ChoicePaidError(Exception):
    """status is the HTTP status (0 if there was no response); code is the API's error code, or network / timeout."""

    def __init__(self, status: int, code: str, message: str):
        super().__init__(message)
        self.status = status
        self.code = code
        self.message = message

    def __repr__(self) -> str:
        return f"ChoicePaidError(status={self.status}, code={self.code!r}, message={self.message!r})"


def _retryable(status: int, code: str) -> bool:
    return status == 0 or status == 429 or status >= 500 or code == "idempotency_in_progress"


class _Resource:
    def __init__(self, client: "ChoicePaid", path: str):
        self._c = client
        self._path = path

    def list(self, **params: Any) -> Dict[str, Any]:
        """One page: {"data": [...], "next_cursor": "..." or None}."""
        return self._c.request("GET", self._path, query=params)

    def list_all(self, **params: Any) -> Iterator[Dict[str, Any]]:
        """Every item across pages, fetched as you go."""
        cursor = None
        while True:
            page = self._c.request("GET", self._path, query={**params, **({"cursor": cursor} if cursor else {})})
            yield from page["data"]
            cursor = page.get("next_cursor")
            if not cursor:
                return


class _Students(_Resource):
    def get(self, id: str) -> Dict[str, Any]:
        return self._c.request("GET", f"{self._path}/{parse.quote(id)}")["data"]

    def create(self, idempotency_key: Optional[str] = None, **body: Any) -> Dict[str, Any]:
        """name and program (slug) are required; parent, grade and family_email are optional."""
        return self._c.request("POST", self._path, body=body, idempotency_key=idempotency_key)["data"]


class _Sessions(_Resource):
    def create(self, idempotency_key: Optional[str] = None, **body: Any) -> Dict[str, Any]:
        """student_id, date (YYYY-MM-DD), description and rate_cents are required."""
        return self._c.request("POST", self._path, body=body, idempotency_key=idempotency_key)["data"]


class _Invoices(_Resource):
    def get(self, id: str) -> Dict[str, Any]:
        return self._c.request("GET", f"{self._path}/{parse.quote(id)}")["data"]

    def update(self, id: str, idempotency_key: Optional[str] = None, **body: Any) -> Dict[str, Any]:
        """status (with on, reason, rejection_code) and/or reference."""
        return self._c.request("PATCH", f"{self._path}/{parse.quote(id)}", body=body, idempotency_key=idempotency_key)["data"]

    def mark_paid(self, id: str, on: Optional[str] = None, idempotency_key: Optional[str] = None) -> Dict[str, Any]:
        return self.update(id, idempotency_key=idempotency_key, status="paid", **({"on": on} if on else {}))


class ChoicePaid:
    def __init__(self, api_key: str, base_url: str = DEFAULT_BASE_URL, max_retries: int = 2, timeout: float = 30.0):
        if not re.fullmatch(r"cp_(live|test)_[A-Za-z0-9_-]{20,64}", api_key or ""):
            raise ChoicePaidError(0, "invalid", "Pass a ChoicePaid API key (cp_live_... or cp_test_...).")
        self._key = api_key
        self.livemode = api_key.startswith("cp_live_")
        self.base_url = base_url.rstrip("/")
        self.max_retries = max(0, max_retries)
        self.timeout = timeout
        self.students = _Students(self, "/students")
        self.sessions = _Sessions(self, "/sessions")
        self.invoices = _Invoices(self, "/invoices")

    def me(self) -> Dict[str, Any]:
        return self.request("GET", "/me")

    def request(self, method: str, path: str, query: Optional[Dict[str, Any]] = None, body: Optional[Dict[str, Any]] = None, idempotency_key: Optional[str] = None) -> Any:
        q = {k: ("true" if v is True else "false" if v is False else v) for k, v in (query or {}).items() if v is not None and v != ""}
        url = self.base_url + path + (f"?{parse.urlencode(q)}" if q else "")
        write = method != "GET"
        headers = {"Authorization": f"Bearer {self._key}", "Accept": "application/json", "User-Agent": f"choicepaid-python/{__version__}"}
        data = None
        if write:
            headers["Content-Type"] = "application/json"
            headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
            data = json.dumps(body or {}).encode()
        attempt = 0
        while True:
            status, code, message, retry_after = 0, "network", "The request didn't reach ChoicePaid.", 0.0
            try:
                with request.urlopen(request.Request(url, data=data, method=method, headers=headers), timeout=self.timeout) as res:
                    return json.loads(res.read() or b"null")
            except error.HTTPError as e:
                status = e.code
                try:
                    err = json.loads(e.read() or b"{}").get("error") or {}
                except ValueError:
                    err = {}
                code = err.get("code") or f"http_{e.code}"
                message = err.get("message") or f"ChoicePaid returned HTTP {e.code}."
                try:
                    retry_after = float(e.headers.get("Retry-After") or 0)
                except ValueError:
                    retry_after = 0.0
            except TimeoutError:
                code, message = "timeout", f"No response within {self.timeout} seconds."
            except error.URLError as e:
                if isinstance(getattr(e, "reason", None), TimeoutError):
                    code, message = "timeout", f"No response within {self.timeout} seconds."
            if attempt >= self.max_retries or not _retryable(status, code):
                raise ChoicePaidError(status, code, message)
            attempt += 1
            time.sleep(min(retry_after, 60) if retry_after else min(8.0, 0.5 * 2 ** (attempt - 1)) * (0.75 + random.random() / 2))


def verify_webhook(raw_body: bytes | str, signature_header: Optional[str], secret: str, tolerance_seconds: int = 300) -> Dict[str, Any]:
    """Check ChoicePaid-Signature against the raw request body and return the parsed event.

    Raises ChoicePaidError(code="invalid_signature") if the signature doesn't match or is too old.
    """
    body = raw_body.decode() if isinstance(raw_body, bytes) else raw_body
    parts = dict(p.strip().split("=", 1) for p in (signature_header or "").split(",") if "=" in p)
    try:
        t = int(parts.get("t", "0"))
    except ValueError:
        t = 0
    if not t or not parts.get("v1"):
        raise ChoicePaidError(400, "invalid_signature", "Missing or malformed ChoicePaid-Signature header.")
    if abs(time.time() - t) > tolerance_seconds:
        raise ChoicePaidError(400, "invalid_signature", "Signature timestamp is too old (possible replay).")
    expected = hmac.new(secret.encode(), f"{t}.{body}".encode(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, parts["v1"]):
        raise ChoicePaidError(400, "invalid_signature", "Signature doesn't match. Check the signing secret and that you passed the raw body.")
    return json.loads(body)
