import threading

from grayloghelper import EdpLogTypeFilter, set_log_fields


def test_enriches_record_with_every_inner_filter(make_record, monkeypatch):
    monkeypatch.setenv("GRAYLOG_FIELD_REGION", "br-sp")
    threading.current_thread()._edp_context_name = "tenant-A"
    set_log_fields(order_id="o-1")

    rec = make_record(thread_name="MessageProcessorThread$OrderProcessor$req-42")
    EdpLogTypeFilter(log_source="svc", app="checkout").filter(rec)

    assert rec.log_level == "INFO"
    assert rec.thread_id == rec.thread
    assert 1 <= rec.count <= 99
    assert rec.threadName == "MessageProcessorThread"
    assert rec.processor_name == "OrderProcessor"
    assert rec.request_id == "req-42"
    assert rec.log_source == "svc"
    assert rec.log_type == "edp-log-type-gelf"
    assert rec.log_verion == "1.0"
    assert rec.app == "checkout"
    assert rec.region == "br-sp"
    assert rec.context_name == "tenant-A"
    assert rec.order_id == "o-1"


def test_filter_returns_truthy_so_record_is_emitted(make_record):
    rec = make_record()
    assert EdpLogTypeFilter(log_source="svc").filter(rec) == 1


def test_works_with_minimal_setup(make_record):
    """No env vars, no context, no log fields, no MessageProcessorThread name."""
    rec = make_record(thread_name="MainThread")
    EdpLogTypeFilter(log_source="svc").filter(rec)

    assert rec.log_level == "INFO"
    assert rec.log_source == "svc"
    assert rec.threadName == "MainThread"
    assert not hasattr(rec, "processor_name")
    assert not hasattr(rec, "context_name")


def test_dynamic_fields_override_fixed_fields(make_record):
    """DynamicLogFieldsFilter runs last, so its values win on collisions."""
    set_log_fields(app="overridden")
    rec = make_record()
    EdpLogTypeFilter(log_source="svc", app="default").filter(rec)
    assert rec.app == "overridden"
