"""OAuth2 client credentials token acquisition via the API's /token proxy."""

from __future__ import annotations

import requests

from .exceptions import APIError


class Authenticator:
    """Fetches short-lived access tokens via the API's token proxy endpoint."""

    def __init__(
        self,
        api_url: str,
        client_id: str,
        client_secret: str,
        scope_override: str | None = None,
    ) -> None:
        self._token_url = f"{api_url.rstrip('/')}/token"
        self._client_id = client_id
        self._client_secret = client_secret
        self._scope_override = scope_override

    def get_token(self, scope: str) -> str:
        resp = requests.post(
            self._token_url,
            json={
                "client_id": self._client_id,
                "client_secret": self._client_secret,
                "scope": self._scope_override or scope,
            },
        )
        if resp.status_code >= 400:
            raise APIError(resp.status_code, f"Token request failed: {resp.text}")
        return resp.json()["access_token"]
