"""
This program has been developed by students from the bachelor Computer Science at Utrecht
University within the Software Project course.
© Copyright Utrecht University (Department of Information and Computing Sciences)
"""

import logging

import pytest

from control_backend.logging import PartialFilter


@pytest.fixture
def logger():
    """Create a fresh logger for each test."""
    logger = logging.getLogger(f"test_{id(object())}")
    logger.setLevel(logging.DEBUG)
    logger.handlers = []
    return logger


@pytest.fixture
def log_output(logger):
    """Capture log output and return a function to get it."""

    class ListHandler(logging.Handler):
        def __init__(self):
            super().__init__()
            self.records = []

        def emit(self, record):
            self.records.append(self.format(record))

    handler = ListHandler()
    handler.addFilter(PartialFilter())
    handler.setFormatter(logging.Formatter("%(message)s"))
    logger.addHandler(handler)

    return lambda: handler.records


def test_no_partial_attribute(logger, log_output):
    """Records without partial attribute should pass through."""
    logger.info("normal message")

    assert log_output() == ["normal message"]


def test_partial_true_filtered(logger, log_output):
    """Records with partial=True should be filtered out."""
    logger.info("partial message", extra={"partial": True})

    assert log_output() == []


def test_partial_false_passes(logger, log_output):
    """Records with partial=False should pass through."""
    logger.info("complete message", extra={"partial": False})

    assert log_output() == ["complete message"]


def test_partial_none_passes(logger, log_output):
    """Records with partial=None should pass through."""
    logger.info("message", extra={"partial": None})

    assert log_output() == ["message"]


def test_partial_truthy_value_passes(logger, log_output):
    """
    Records with truthy but non-True partial should pass through, that is, only when it's exactly
    ``True`` should it pass.
    """
    logger.info("message", extra={"partial": "yes"})

    assert log_output() == ["message"]


def test_multiple_records_mixed(logger, log_output):
    """Filter should handle mixed records correctly."""
    logger.info("first")
    logger.info("second", extra={"partial": True})
    logger.info("third", extra={"partial": False})
    logger.info("fourth", extra={"partial": True})
    logger.info("fifth")

    assert log_output() == ["first", "third", "fifth"]
