"""
Utility functions for LaneSwap client library.

This module provides environment variable helpers and common utilities
used throughout the library.
"""

import logging
import os
import sys
from typing import Optional


def get_service_name(override: Optional[str] = None) -> str:
    """
    Get service name from environment or override.

    Args:
        override: Optional service name to use instead of environment variable

    Returns:
        Service name from override, SERVICE_NAME env var, or default "service"

    Examples:
        >>> get_service_name()  # Uses SERVICE_NAME env var
        'my-service'
        >>> get_service_name("custom-service")  # Uses override
        'custom-service'
    """
    if override is not None:
        return override
    return os.getenv("SERVICE_NAME", "service")


def get_port(override: Optional[int] = None) -> int:
    """
    Get port number from environment or override.

    Args:
        override: Optional port number to use instead of environment variable

    Returns:
        Port number from override, PORT env var, or default 5000

    Raises:
        ValueError: If PORT environment variable is not a valid integer

    Examples:
        >>> get_port()  # Uses PORT env var
        5000
        >>> get_port(8080)  # Uses override
        8080
    """
    if override is not None:
        return override

    port_str = os.getenv("PORT", "5000")
    try:
        return int(port_str)
    except ValueError as e:
        raise ValueError(f"Invalid PORT environment variable: {port_str!r}") from e


def setup_logging(level: Optional[str] = None) -> logging.Logger:
    """
    Configure logging for LaneSwap-managed services.

    Args:
        level: Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
               Defaults to LOG_LEVEL env var or INFO

    Returns:
        Configured logger instance

    Examples:
        >>> logger = setup_logging()
        >>> logger.info("Service starting")
        2025-01-17 10:00:00,000 [INFO] Service starting
    """
    if level is None:
        level = os.getenv("LOG_LEVEL", "INFO")

    # Convert string level to logging constant
    numeric_level = getattr(logging, level.upper(), logging.INFO)

    # Configure root logger
    logging.basicConfig(
        level=numeric_level,
        format="%(asctime)s [%(levelname)s] %(message)s",
        handlers=[logging.StreamHandler(sys.stdout)],
        force=True,  # Override any existing configuration
    )

    return logging.getLogger(__name__)


def get_logger(name: Optional[str] = None) -> logging.Logger:
    """
    Get a logger instance.

    Args:
        name: Logger name. Defaults to __name__ of caller

    Returns:
        Logger instance

    Examples:
        >>> logger = get_logger("my-service")
        >>> logger.info("Message")
    """
    return logging.getLogger(name or "laneswap")
