"""
Utility functions for reading environment variables.
"""
import os
from typing import Optional

from dotenv import load_dotenv

# Load .env file automatically when module is imported
load_dotenv()


def get_string_env_var(
    var_name: str, default: Optional[str] = None, is_mandatory: bool = True
) -> Optional[str]:
    """
    Get a string environment variable.

    Args:
        var_name: Name of the environment variable
        default: Default value if variable is not set
        is_mandatory: Whether the variable is required

    Returns:
        The environment variable value or default

    Raises:
        ValueError: If variable is mandatory and not set and no default provided
    """
    value = os.getenv(var_name, default)
    if value is None and is_mandatory:
        raise ValueError(f'Environment variable {var_name} is not set')
    return value


def get_int_env_var(
    var_name: str, default: Optional[int] = None, is_mandatory: bool = True
) -> Optional[int]:
    """
    Get an integer environment variable.

    Args:
        var_name: Name of the environment variable
        default: Default value if variable is not set
        is_mandatory: Whether the variable is required

    Returns:
        The environment variable value as integer or default

    Raises:
        ValueError: If variable is mandatory and not set and no default provided, or cannot be converted to int
    """
    value = os.getenv(var_name)
    if value is None:
        if default is None and is_mandatory:
            raise ValueError(f'Environment variable {var_name} is not set')
        return default
    try:
        return int(value)
    except ValueError:
        raise ValueError(
            f'Environment variable {var_name} must be an integer, got: {value}'
        )
