"""Logging helpers for a24wh."""

import logging
from pathlib import Path

from .config import get_config
from .constants import LOGGER_NAME, LOG_FORMAT

_AUTO_CONFIGURED = False


def get_logger() -> logging.Logger:
    logger = logging.getLogger(LOGGER_NAME)
    if not any(isinstance(handler, logging.NullHandler) for handler in logger.handlers):
        logger.addHandler(logging.NullHandler())
    return logger


def configure_local_logging(
        level: str | int | None = None,
        *,
        log_to_console: bool | None = None,
        log_to_file: bool | None = None,
        log_file: str | None = None,
        ) -> logging.Logger:
    config = get_config()
    logger = logging.getLogger(LOGGER_NAME)
    logger.handlers = []
    logger.propagate = False

    resolved_level = level or config.log_level
    logger.setLevel(resolved_level)

    formatter = logging.Formatter(LOG_FORMAT)

    use_console = config.log_to_console if log_to_console is None else log_to_console
    if use_console:
        console_handler = logging.StreamHandler()
        console_handler.setLevel(resolved_level)
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)

    use_file = config.log_to_file if log_to_file is None else log_to_file
    if use_file:
        file_path = Path(log_file or config.log_file)
        file_handler = logging.FileHandler(file_path, encoding="utf-8")
        file_handler.setLevel(resolved_level)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)

    if not logger.handlers:
        logger.addHandler(logging.NullHandler())

    return logger


def auto_configure_logging() -> logging.Logger:
    global _AUTO_CONFIGURED
    if _AUTO_CONFIGURED:
        return logging.getLogger(LOGGER_NAME)

    config = get_config()
    if config.auto_configure_logging:
        logger = configure_local_logging()
    else:
        logger = get_logger()

    _AUTO_CONFIGURED = True
    return logger
