import logging

from ..config.env_bool import env_bool
from ..config.environment_variables import FRISK_DEBUG


def auto_enable_debug_logging(base_logger_name: str) -> None:
    """Enable Frisk debug logging when ``FRISK_DEBUG`` is truthy."""
    # 1) Decide if debug is enabled
    debug = env_bool(FRISK_DEBUG)
    if not debug:
        return

    base_logger = logging.getLogger(base_logger_name)
    base_logger.setLevel(logging.DEBUG)

    root = logging.getLogger()

    # 2) If the app already configured logging, don't add handlers.
    # (Their handlers/formatters should apply via propagation.)
    if root.handlers:
        return

    # 3) If *no one* configured logging, install a simple console handler
    # just for Frisk to make debug "just work".
    handler = logging.StreamHandler()
    handler.setLevel(logging.DEBUG)
    handler.setFormatter(
        logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s")
    )

    base_logger.addHandler(handler)
    base_logger.propagate = False  # avoid duplicates if app later calls basicConfig()
