"""
Logging utilities for pyulysses.
"""
import logging
import sys
from typing import Optional


class UlyssesLogger:
    """Constants for Ulysses logging configuration."""

    LOGGING_LEVEL = 'ULYSSES_LOGGING_LEVEL'
    DEFAULT_LOGGING_LEVEL = 'INFO'


def set_logging_level(level_string: str, module_name: str) -> logging.Logger:
    """
    Configure and get a logger with the specified level.

    Args:
        level_string: Logging level as string (DEBUG, INFO, WARNING, ERROR, CRITICAL)
        module_name: Name of the module for the logger

    Returns:
        Configured logger instance
    """
    # Convert string level to logging constant
    level_map = {
        'DEBUG': logging.DEBUG,
        'INFO': logging.INFO,
        'WARNING': logging.WARNING,
        'ERROR': logging.ERROR,
        'CRITICAL': logging.CRITICAL,
    }

    level = level_map.get(level_string.upper(), logging.INFO)

    logger = logging.getLogger(module_name)
    logger.setLevel(level)

    # Only add handler if logger doesn't have handlers yet
    if not logger.handlers:
        # Create console handler
        handler = logging.StreamHandler(sys.stdout)
        handler.setLevel(level)

        # Create formatter
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S',
        )
        handler.setFormatter(formatter)

        # Add handler to logger
        logger.addHandler(handler)

    return logger


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

    Args:
        name: Name of the logger
        level: Logging level (default: INFO)

    Returns:
        Configured logger instance
    """
    if level is None:
        level = logging.INFO

    logger = logging.getLogger(name)
    logger.setLevel(level)

    # Only add handler if logger doesn't have handlers yet
    if not logger.handlers:
        # Create console handler
        handler = logging.StreamHandler(sys.stdout)
        handler.setLevel(level)

        # Create formatter
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S',
        )
        handler.setFormatter(formatter)

        # Add handler to logger
        logger.addHandler(handler)

    return logger
