"""
Get OAuth Access Token - Python Example

Exchange M2M client credentials for an access token
using the OAuth 2.0 Client Credentials flow.

SETUP: Set environment variables before running:
  # Token endpoint URL is issued with your M2M credentials
  export OAUTH_TOKEN_ENDPOINT="{token-endpoint}"
  export OAUTH_CLIENT_ID="your-client-id"
  export OAUTH_CLIENT_SECRET="your-client-secret"
"""

import os
import requests
from typing import Dict

# Configuration - Load from environment variables (raises KeyError if missing)
OAUTH_TOKEN_ENDPOINT = os.environ["OAUTH_TOKEN_ENDPOINT"]
CLIENT_ID = os.environ["OAUTH_CLIENT_ID"]
CLIENT_SECRET = os.environ["OAUTH_CLIENT_SECRET"]
SCOPES = os.environ.get("OAUTH_SCOPES", "crm-api/products.read")


def get_access_token() -> str:
    """
    Get an access token using client credentials.

    Returns:
        str: The access token (JWT)

    Raises:
        requests.HTTPError: If the token request fails
    """
    # Prepare request data (URL-encoded)
    data = {
        "grant_type": "client_credentials",
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "scope": SCOPES,
    }

    # Make token request
    response = requests.post(
        OAUTH_TOKEN_ENDPOINT,
        data=data,
        headers={"Content-Type": "application/x-www-form-urlencoded"},
    )

    # Handle errors
    if response.status_code != 200:
        error_data = response.json()
        raise requests.HTTPError(
            f"Token request failed: {error_data.get('error')} - "
            f"{error_data.get('error_description')}"
        )

    # Parse response
    token_data = response.json()
    access_token = token_data["access_token"]
    token_type = token_data["token_type"]
    expires_in = token_data["expires_in"]

    print("✅ Access token obtained successfully")
    print(f"Token type: {token_type}")
    print(f"Expires in: {expires_in} seconds ({expires_in / 60:.0f} minutes)")
    print(f"Access token: {access_token[:50]}...")

    return access_token


if __name__ == "__main__":
    try:
        token = get_access_token()
        print("\n📋 Use this token in API requests:")
        print(f"Authorization: Bearer {token[:50]}...")
    except Exception as e:
        print(f"❌ Error: {e}")
        exit(1)
