import logging
import sys

from meshnet_tracker.logging_setup import configure_tracker_file_logging, tracker_logger


def test_tracker_file_logging_writes_separate_level_files(tmp_path):
    "Tracker file logging writes separate level files\n\nTags: routing, tracker"
    original_stdout = sys.stdout
    original_stderr = sys.stderr
    try:
        log_dir = configure_tracker_file_logging(tmp_path, tee_stdio=False)
        logger = tracker_logger()

        logger.info("info-event")
        logger.warning("warning-event")
        logger.error("error-event")
        for handler in logger.handlers:
            handler.flush()

        assert (log_dir / "info.log").read_text().count("info-event") == 1
        assert "warning-event" not in (log_dir / "info.log").read_text()
        assert "error-event" not in (log_dir / "info.log").read_text()

        assert "warning-event" in (log_dir / "warning.log").read_text()
        assert "info-event" not in (log_dir / "warning.log").read_text()
        assert "error-event" not in (log_dir / "warning.log").read_text()

        assert "error-event" in (log_dir / "error.log").read_text()
        assert "info-event" not in (log_dir / "error.log").read_text()
        assert "warning-event" not in (log_dir / "error.log").read_text()
    finally:
        sys.stdout = original_stdout
        sys.stderr = original_stderr


def test_tracker_file_logging_tees_stdio_and_rotates(tmp_path):
    "Tracker file logging tees stdio and rotates\n\nTags: routing, tracker"
    original_stdout = sys.stdout
    original_stderr = sys.stderr
    try:
        log_dir = configure_tracker_file_logging(
            tmp_path,
            max_bytes=120,
            backup_count=1,
        )

        print("stdout goes to info", flush=True)
        print("stderr goes to error", file=sys.stderr, flush=True)
        for handler in tracker_logger().handlers:
            handler.flush()

        assert "stdout goes to info" in (log_dir / "info.log").read_text()
        assert "stderr goes to error" in (log_dir / "error.log").read_text()

        for index in range(12):
            tracker_logger().info("rotating-info-line-%02d", index)
        for handler in tracker_logger().handlers:
            handler.flush()

        assert (log_dir / "info.log.1").exists()
    finally:
        sys.stdout = original_stdout
        sys.stderr = original_stderr
        logger = tracker_logger()
        for handler in logger.handlers:
            handler.close()
        logger.handlers.clear()
        logger.setLevel(logging.NOTSET)
