"""Behaviour of the TimeProcessorCallback: after events are handled it
periodically logs how many were processed and the average time spent.

The callback reports from a background thread on its own interval, so the test
configures a short interval and waits (briefly, with a deadline) for the report.
"""
import logging
import time

from messagebus import Event

from messageprocessorutil import TimeProcessorCallback

from testutil import BaseProcessor

LOGGER_NAME = "messageprocessor.tests.time"


def test_logs_a_count_and_average_time_after_handling_events(build_handler, message_bus, caplog):
    caplog.set_level(logging.INFO, logger=LOGGER_NAME)
    callback = TimeProcessorCallback(logging.getLogger(LOGGER_NAME), log_time=0.05)
    handler = build_handler(event_processors={"orders": BaseProcessor("orders")}, callbacks=[callback])

    handler.handle_event(message_bus, Event("orders", None, b""))
    handler.handle_event(message_bus, Event("orders", None, b""))

    deadline = time.time() + 3.0
    while time.time() < deadline:
        if any("Process average time" in r.getMessage() for r in list(caplog.records)):
            break
        time.sleep(0.02)

    timing_logs = [r for r in caplog.records if "Process average time" in r.getMessage()]
    assert timing_logs, "expected the callback to log the average processing time"
    assert timing_logs[0].levelno == logging.INFO
    assert "Count:" in timing_logs[0].getMessage()
