import logging

import pytest

from logging_config import configure_logging


class TestConfigureLogging:
    def _clear_handlers(self):
        root = logging.getLogger()
        root.handlers.clear()
        root.setLevel(logging.WARNING)

    def test_sets_root_logger_level(self):
        self._clear_handlers()
        configure_logging(level=logging.DEBUG)
        root = logging.getLogger()
        assert root.level == logging.DEBUG

    def test_default_level_is_info(self):
        self._clear_handlers()
        configure_logging()
        root = logging.getLogger()
        assert root.level == logging.INFO

    def test_handler_format_includes_name_and_level(self):
        self._clear_handlers()
        configure_logging()
        root = logging.getLogger()
        assert len(root.handlers) == 1
        handler = root.handlers[0]
        formatter = handler.formatter
        assert formatter is not None
        fmt = formatter._fmt or ""
        assert "%(name)s" in fmt
        assert "%(levelname)s" in fmt
        assert "%(asctime)s" in fmt

    def test_idempotent_second_call(self):
        self._clear_handlers()
        configure_logging()
        initial_handlers = len(logging.getLogger().handlers)
        configure_logging()
        assert len(logging.getLogger().handlers) == initial_handlers

    def test_module_logger_inherits_level(self):
        self._clear_handlers()
        configure_logging(level=logging.WARNING)
        logger = logging.getLogger("some.module")
        assert logger.level == logging.NOTSET
        assert logger.isEnabledFor(logging.WARNING)
        assert not logger.isEnabledFor(logging.INFO)
