import logging
from target_simulator.utils import logger as tlogger
from tkinter import scrolledtext


def test_add_tkinter_handler_and_emit(monkeypatch):
    # Prepare logging system active and a base formatter
    tlogger._logging_system_active = True
    tlogger._base_formatter = logging.Formatter('%(levelname)s:%(message)s')

    # Create a scrolledtext widget (our conftest maps this to DummyWidget)
    widget = scrolledtext.ScrolledText()
    # Ensure widget reports exists
    assert widget.winfo_exists()

    # Provide a logging config with colors
    cfg = {'colors': {logging.INFO: 'black', logging.ERROR: 'red'}}
    # Call add_tkinter_handler should set _actual_tkinter_handler
    tlogger.add_tkinter_handler(widget, cfg)
    assert tlogger._actual_tkinter_handler is not None

    # Emit a record through the handler and ensure widget buffer updated
    rec = logging.LogRecord('x', logging.INFO, '', 0, 'hello', None, None)
    tlogger._actual_tkinter_handler.emit(rec)
    # The DummyWidget stores text in _text
    assert 'hello' in widget.get('1.0', 'end')

    # Cleanup global flags for other tests
    tlogger._actual_tkinter_handler = None
    tlogger._logging_system_active = False
