"""
Environment validation module for MiniMax client library.

This module handles environment variable validation and management,
including HF_TOKEN verification and optional .env file loading.
"""

import logging
import os
import sys
from typing import Optional

# Try to import python-dotenv for .env file support
try:
    from dotenv import load_dotenv
    DOTENV_AVAILABLE = True
except ImportError:
    DOTENV_AVAILABLE = False

logger = logging.getLogger(__name__)


def load_environment_file(env_file: str = ".env") -> bool:
    """
    Load environment variables from a .env file if python-dotenv is available.
    
    Args:
        env_file: Path to the .env file (default: ".env")
        
    Returns:
        bool: True if .env file was loaded successfully, False otherwise
    """
    if not DOTENV_AVAILABLE:
        logger.debug("python-dotenv not available, skipping .env file loading")
        return False
    
    if not os.path.exists(env_file):
        logger.debug(f"No {env_file} file found")
        return False
    
    try:
        load_dotenv(env_file)
        logger.info(f"Successfully loaded environment variables from {env_file}")
        return True
    except Exception as e:
        logger.warning(f"Failed to load {env_file}: {e}")
        return False


def check_environment() -> str:
    """
    Check if the required environment variables are set.
    
    Returns:
        str: The HF_TOKEN value if found
        
    Raises:
        SystemExit: If HF_TOKEN is not set (exit code 2 for configuration errors)
    """
    # Try to load .env file first
    load_environment_file()
    
    hf_token = os.getenv("HF_TOKEN")
    if not hf_token:
        logger.error("HF_TOKEN environment variable is not set")
        logger.error("Please set your Hugging Face API token:")
        logger.error("export HF_TOKEN='your_token_here'")
        logger.error("Or create a .env file with: HF_TOKEN=your_token_here")
        sys.exit(2)  # Exit code 2 for configuration errors
    
    logger.info("✓ HF_TOKEN environment variable found")
    return hf_token


def validate_token_format(token: str) -> bool:
    """
    Validate the format of the HF_TOKEN.
    
    Args:
        token: The Hugging Face API token to validate
        
    Returns:
        bool: True if token format appears valid, False otherwise
    """
    if not token:
        return False
    
    # Basic validation: HF tokens typically start with 'hf_' and are at least 20 characters
    if token.startswith('hf_') and len(token) >= 20:
        return True
    
    # Legacy tokens might not start with 'hf_' but should be reasonably long
    if len(token) >= 20:
        logger.warning("Token format appears to be legacy format (not starting with 'hf_')")
        return True
    
    return False


def get_environment_info() -> dict:
    """
    Get information about the current environment setup.
    
    Returns:
        dict: Dictionary containing environment information
    """
    return {
        "hf_token_set": bool(os.getenv("HF_TOKEN")),
        "dotenv_available": DOTENV_AVAILABLE,
        "env_file_exists": os.path.exists(".env"),
        "python_version": sys.version,
        "platform": sys.platform
    }