"""
@description Grubtech API Authentication - Python
@author Grubtech Integration Team
@version 1.0.0

This example demonstrates how to authenticate with the Grubtech API
using an API key to obtain an access token.

Prerequisites:
- Python 3.8+
- requests library (pip install requests)
- Valid Grubtech API key

Replace the following placeholders:
- {{API_KEY}}: Your Grubtech API key
- {{PARTNER_ID}}: Your partner identifier
"""

import requests
import sys
from typing import Dict, Any

API_KEY = '{{API_KEY}}'
PARTNER_ID = '{{PARTNER_ID}}'
BASE_URL = 'https://api.staging.grubtech.io'


def authenticate() -> str:
    """
    Authenticate with Grubtech API and obtain access token

    Returns:
        str: Access token for API requests

    Raises:
        Exception: If authentication fails
    """
    try:
        # Construct authentication request
        url = f'{BASE_URL}/v1/auth/token'
        headers = {
            'Content-Type': 'application/json',
            'x-api-key': API_KEY,
        }
        payload = {
            'partnerId': PARTNER_ID,
            'grantType': 'api_key',
        }

        # Make authentication request
        response = requests.post(url, json=payload, headers=headers, timeout=10)

        # Check for errors
        if not response.ok:
            raise Exception(
                f'Authentication failed: {response.status_code} - {response.text}'
            )

        # Extract token from response
        data: Dict[str, Any] = response.json()
        token = data['token']
        expires_in = data.get('expiresIn', 'unknown')

        print(f'Authentication successful!')
        print(f'Token expires in: {expires_in} seconds')

        return token

    except requests.RequestException as e:
        print(f'Authentication error: {e}', file=sys.stderr)
        raise
    except Exception as e:
        print(f'Unexpected error: {e}', file=sys.stderr)
        raise


def example_api_call(token: str) -> Dict[str, Any]:
    """
    Example: Use token in subsequent API requests

    Args:
        token: Access token from authenticate()

    Returns:
        API response data
    """
    url = f'{BASE_URL}/v1/menus'
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json',
    }

    response = requests.get(url, headers=headers, timeout=10)

    if not response.ok:
        raise Exception(f'API call failed: {response.status_code}')

    return response.json()


if __name__ == '__main__':
    try:
        # Authenticate and get token
        access_token = authenticate()

        # Use token for API calls
        menus = example_api_call(access_token)
        print(f'Menus: {menus}')

    except Exception as e:
        sys.exit(1)
