import logging

import pytest

from schedint.logging_config import LOGGER_NAME, configure_logging, get_logger


@pytest.fixture(autouse=True)
def reset_schedint_logger():
    """ """
    logger = logging.getLogger(LOGGER_NAME)

    for this_handler in list(logger.handlers):
        logger.removeHandler(this_handler)

        try:
            this_handler.close()
        except Exception:
            pass

    logger.setLevel(logging.NOTSET)
    logger.propagate = True

    yield

    for this_handler in list(logger.handlers):
        logger.removeHandler(this_handler)

        try:
            this_handler.close()
        except Exception:
            pass


def test_get_logger_namespace_root():
    logger = get_logger()
    assert logger.name == LOGGER_NAME


def test_get_logger_namespace_child():
    logger = get_logger("core.storage")
    assert logger.name == f"{LOGGER_NAME}.core.storage"


def test_configure_logging_adds_single_handler():
    logger = logging.getLogger(LOGGER_NAME)
    assert len(logger.handlers) == 0

    configure_logging(level="INFO")
    assert len(logger.handlers) == 1

    configure_logging(level="DEBUG")
    assert len(logger.handlers) == 1


def test_configure_logging_sets_propagate_false():
    logger = logging.getLogger(LOGGER_NAME)

    configure_logging(level="INFO")
    assert logger.propagate is False


def test_logs_are_emitted_under_schedint_namespace(caplog):
    configure_logging(level="INFO")

    base_logger = logging.getLogger(LOGGER_NAME)
    old_propagate = base_logger.propagate
    base_logger.propagate = True

    try:
        logger = get_logger("core")

        with caplog.at_level(logging.INFO):
            logger.info("hello world")
    finally:
        base_logger.propagate = old_propagate

    assert any("hello world" in rec.message for rec in caplog.records)
    assert any(rec.name == f"{LOGGER_NAME}.core" for rec in caplog.records)


def test_logs_below_level_are_not_emitted(caplog):
    configure_logging(level="INFO")
    logger = get_logger("core")

    with caplog.at_level(logging.DEBUG, logger=LOGGER_NAME):
        logger.debug("debug msg")

    assert not any("debug msg" in rec.message for rec in caplog.records)
