"""Tests for the unified logging configuration."""

import logging
import os
import time

import pytest

from mcard.config.config_constants import DEFAULT_LOG_PATH, LOG_DIRECTORY, LOG_FILENAME
from mcard.config.logging import (
    PerformanceTimer,
    get_logger,
    get_logging_config,
    setup_logging,
)


@pytest.fixture(scope="module", autouse=True)
def setup_module():
    """Create logs directory and initialize logging before tests."""
    os.makedirs(LOG_DIRECTORY, exist_ok=True)
    # Force reinit to ensure clean state
    setup_logging(force_reinit=True)


def test_logging_initialization():
    """Test that logging is properly initialized with correct levels."""
    logger = logging.getLogger("mcard")
    # Check effective level since the logger may inherit from parent
    assert (
        logger.getEffectiveLevel() == logging.DEBUG
    ), "Effective log level should be DEBUG"


def test_logging_config_structure():
    """Test that the logging config has expected structure."""
    config = get_logging_config()

    # Check formatters
    assert "simple" in config["formatters"]
    assert "detailed" in config["formatters"]
    assert "json" in config["formatters"]

    # Check handlers
    assert "console" in config["handlers"]
    assert "file" in config["handlers"]
    assert "error_file" in config["handlers"]

    # Check loggers
    assert "mcard" in config["loggers"]
    assert "mcard.api" in config["loggers"]
    assert "mcard.performance" in config["loggers"]


def test_log_file_creation():
    """Test that log file is created."""
    if not os.path.exists(DEFAULT_LOG_PATH):
        open(DEFAULT_LOG_PATH, "w").close()
    assert os.path.exists(DEFAULT_LOG_PATH), "Log file should be created"


def test_logging_output():
    """Test that logging produces output in the log file."""
    setup_logging(force_reinit=True)

    logger = get_logger("mcard")

    # Create a unique test message
    test_message = f"Test message from unified logging - {time.time()}"
    logger.info(test_message)

    # Force flush all handlers
    for handler in logger.handlers:
        handler.flush()

    time.sleep(0.5)

    log_file_path = os.path.join(
        os.path.dirname(os.path.dirname(__file__)), LOG_DIRECTORY, LOG_FILENAME
    )
    log_file_path = os.path.abspath(log_file_path)

    if os.path.exists(log_file_path):
        with open(log_file_path) as log_file:
            log_contents = log_file.read()
            assert test_message in log_contents, "Test message not found in log file"
    else:
        assert False, f"Log file was not created at {log_file_path}"


def test_default_log_level():
    """Test that the default log level is DEBUG for mcard logger."""
    os.environ.pop("MCARD_SERVICE_LOG_LEVEL", None)
    setup_logging(force_reinit=True)

    logger = logging.getLogger("mcard")
    # Use getEffectiveLevel() to get the actual applied level
    assert (
        logger.getEffectiveLevel() == logging.DEBUG
    ), "Default effective log level should be DEBUG"


def test_logger_retrieval():
    """Test that loggers are retrieved correctly."""
    logger = get_logger("mcard.test")
    assert logger.name == "mcard.test", "Should retrieve the correct logger"


def test_performance_timer():
    """Test the PerformanceTimer context manager."""
    logger = get_logger("mcard.performance")
    original_level = logger.level
    logger.setLevel(logging.DEBUG)

    try:
        with PerformanceTimer("test_operation"):
            time.sleep(0.01)  # Small delay to ensure measurable time
    finally:
        logger.setLevel(original_level)
