from __future__ import annotations

import logging
from io import StringIO

from sync_state_machine.pipeline.run_logger import clear_pipeline_logger_handlers, init_pipeline_logger


def test_suppress_node_logs_filter_works() -> None:
    logger = logging.getLogger("sync_state_machine")
    clear_pipeline_logger_handlers(logger)

    stream = StringIO()
    handler = logging.StreamHandler(stream)
    handler.setFormatter(logging.Formatter("%(message)s"))

    # init and then replace default console handler with our capture handler carrying same filter behavior
    logger = init_pipeline_logger(level=logging.INFO, mirror_console=False, replace_handlers=True, suppress_node_logs=True)
    clear_pipeline_logger_handlers(logger)
    logger.addHandler(handler)

    class _LocalFilter(logging.Filter):
        def filter(self, record: logging.LogRecord) -> bool:
            msg = record.getMessage()
            if "node=" in msg:
                return False
            if "节点 " in msg and "状态" in msg:
                return False
            return True

    handler.addFilter(_LocalFilter())

    logger.info("[company] 自动绑定阻断: node=abc, reason=exists")
    logger.info("✅ Strategy bind: company")

    output = stream.getvalue()
    assert "node=abc" not in output
    assert "Strategy bind: company" in output

    clear_pipeline_logger_handlers(logger)
