"""
Client initialization module for MiniMax client library.

This module handles the initialization of the Hugging Face InferenceClient
with proper error handling, logging, and configuration management.
"""

import logging
import sys
from typing import Optional

import requests
from huggingface_hub import InferenceClient

# Try to import exceptions, fall back to generic Exception if not available
try:
    from huggingface_hub.utils import HfHubHTTPError, RepositoryNotFoundError, GatedRepoError
except ImportError:
    # Fallback for older versions
    HfHubHTTPError = Exception
    RepositoryNotFoundError = Exception
    GatedRepoError = Exception

from .config import Configuration

logger = logging.getLogger(__name__)


def initialize_client(api_key: str, config: Configuration) -> InferenceClient:
    """
    Initialize the Hugging Face Inference Client with proper error handling.
    
    Args:
        api_key: The Hugging Face API token
        config: Configuration object containing client settings
        
    Returns:
        InferenceClient: Configured inference client
        
    Raises:
        SystemExit: With specific exit codes for different error types:
            - 3: Network errors
            - 4: Authentication errors
    """
    try:
        logger.info("Initializing InferenceClient...")
        
        # Initialize the InferenceClient with configurable provider and API key
        client = InferenceClient(
            provider=config.provider,
            token=api_key
        )
        
        logger.info("✓ InferenceClient initialized successfully")
        return client
        
    except ValueError as e:
        # Authentication or parameter validation errors
        logger.error(f"Authentication or parameter error: {e}")
        logger.error("Please check your API token and configuration settings")
        sys.exit(4)
        
    except (requests.exceptions.RequestException, 
            requests.exceptions.ConnectionError,
            requests.exceptions.Timeout,
            requests.exceptions.HTTPError) as e:
        # Network-related errors
        logger.error(f"Network error during client initialization: {e}")
        logger.error("Please check your internet connection and try again")
        sys.exit(3)
        
    except HfHubHTTPError as e:
        # HTTP errors from Hugging Face Hub
        if hasattr(e, 'response') and e.response is not None:
            status_code = e.response.status_code
            if status_code == 401:
                logger.error("Authentication failed: Invalid or expired API token")
                logger.error("Please check your HF_TOKEN environment variable")
                sys.exit(4)
            elif status_code == 403:
                logger.error("Access forbidden: Insufficient permissions")
                logger.error("Please check your API token permissions")
                sys.exit(4)
            elif status_code in (503, 504):
                logger.error("Service temporarily unavailable")
                logger.error("Please try again later")
                sys.exit(3)
            else:
                logger.error(f"HTTP error during client initialization: {e}")
                sys.exit(3)
        else:
            logger.error(f"HTTP error during client initialization: {e}")
            sys.exit(3)
            
    except (RepositoryNotFoundError, GatedRepoError) as e:
        # Repository access errors
        logger.error(f"Repository access error: {e}")
        logger.error("Please check your API token and repository permissions")
        sys.exit(4)
        
    except Exception as e:
        # Catch any other unexpected errors
        logger.error(f"Unexpected error during client initialization: {e}")
        logger.error("Please check your configuration and try again")
        sys.exit(1)