"""
Logger initialization module.

This module provides functions for setting up a structured logger with a
JSON formatter. It initializes a default logger that can be used throughout

Functions:
    get_log_name() -> str: Get the logger's name.
    get_log_level(level: Optional[str]) -> str: Get the log level.
    setup_logger(name: Optional[str], level: Optional[str]) -> logging.Logger: Set up and configure the logger.
"""


import os
import logging

from jt_logger import formatter
from jt_logger import structured_logger


def get_log_name():
    """
    Retrieve the name for the logger.

    Returns:
        str: Logger name, defaulting to the environment variable 'LOG_NAME'
             or the module's __name__.
    """

    return os.getenv('LOG_NAME', __name__)


def get_log_level(level=None):
    """
    Retrieve the logging level.

    Args:
        level (Optional[str]): Log level to use. If not provided, it falls back
                               to the environment variable 'LOG_LEVEL' or 'DEBUG'.

    Returns:
        str: The log level to be used.
    """

    return level if level else os.getenv('LOG_LEVEL', 'DEBUG')


def setup_logger(name=None, level=None):
    """
    Set up and configure the structured logger with a JSON formatter.

    Args:
        name (Optional[str]): Name of the logger. Defaults to None, which falls
                              back to the result of get_log_name().
        level (Optional[str]): Log level to use. Defaults to None, which falls
                               back to the result of get_log_level().

    Returns:
        logging.Logger: Configured logger instance.
    """

    log_name = name if name else get_log_name()
    logger = structured_logger.StructuredLogger(log_name)
    handler = logging.StreamHandler()
    handler.setFormatter(formatter.JsonFormatter())
    logger.addHandler(handler)
    logger.setLevel(get_log_level(level))
    return logger


log = setup_logger()


# That's all folks...
