import base64
import hashlib
import secrets

# === Constants ===

_VERIFIER_BYTES = 64
_STATE_BYTES = 32


# === Helpers ===


def _base64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")


# === PKCE ===


def generate_verifier() -> str:
    """Generate a PKCE code verifier (43-128 URL-safe chars)."""
    return _base64url(secrets.token_bytes(_VERIFIER_BYTES))


def generate_challenge(verifier: str) -> str:
    """Generate S256 code challenge for a verifier."""
    digest = hashlib.sha256(verifier.encode("ascii")).digest()
    return _base64url(digest)


def generate_state() -> str:
    """Generate a random OAuth state value."""
    return _base64url(secrets.token_bytes(_STATE_BYTES))
