"""
Tests for the unified logging configuration.

This tests the canonical logging module: mcard.config.logging
"""

import logging
import time

import pytest

from mcard.config.logging import (
    PerformanceTimer,
    SecurityAuditLogger,
    get_database_logger,
    get_logger,
    get_performance_logger,
    get_security_logger,
    setup_logging,
)


class TestImprovedLogging:
    """Test suite for unified logging functionality."""

    def test_setup_improved_logging(self):
        """Test that logging setup works correctly."""
        setup_logging(force_reinit=True)

        # Verify loggers are configured
        logger = get_logger("test")
        assert logger is not None
        assert isinstance(logger, logging.Logger)

    def test_specialized_loggers(self):
        """Test that specialized loggers are available."""
        setup_logging(force_reinit=True)

        perf_logger = get_performance_logger()
        security_logger = get_security_logger()
        db_logger = get_database_logger()

        assert perf_logger.name == "mcard.performance"
        assert security_logger.name == "mcard.security"
        assert db_logger.name == "mcard.database"

    def test_performance_timer(self):
        """Test performance timing functionality."""
        setup_logging(force_reinit=True)

        with PerformanceTimer("test_operation"):
            time.sleep(0.01)  # Small delay for testing

        # Timer should complete without errors

    def test_security_audit_logger(self):
        """Test security audit logging functionality."""
        setup_logging(force_reinit=True)

        security = SecurityAuditLogger()

        # Test different security logging methods
        security.log_access_attempt("test_user", "/test/resource", success=True)
        security.log_authentication("test_user", "password", success=True)
        security.log_suspicious_activity("Test activity", "Test details")

    def test_log_levels(self):
        """Test different log levels work correctly."""
        setup_logging(force_reinit=True)

        logger = get_logger("test.levels")

        # Test all log levels
        logger.debug("Debug message")
        logger.info("Info message")
        logger.warning("Warning message")
        logger.error("Error message")
        logger.critical("Critical message")

    def test_logger_hierarchy(self):
        """Test that logger hierarchy works correctly."""
        setup_logging(force_reinit=True)

        # Test different logger names
        api_logger = get_logger("mcard.api")
        db_logger = get_logger("mcard.database")
        custom_logger = get_logger("mcard.custom.module")

        assert api_logger.name == "mcard.api"
        assert db_logger.name == "mcard.database"
        assert custom_logger.name == "mcard.custom.module"

    def test_exception_logging(self):
        """Test that exceptions are logged correctly."""
        setup_logging(force_reinit=True)

        logger = get_logger("test.exceptions")

        try:
            raise ValueError("Test exception")
        except ValueError:
            logger.error("Test exception occurred", exc_info=True)

    def test_performance_timer_with_exception(self):
        """Test performance timer handles exceptions correctly."""
        setup_logging(force_reinit=True)

        with pytest.raises(ValueError):
            with PerformanceTimer("failing_operation"):
                raise ValueError("Test exception")

    def test_multiple_loggers(self):
        """Test that multiple loggers can be used simultaneously."""
        setup_logging(force_reinit=True)

        logger1 = get_logger("test.module1")
        logger2 = get_logger("test.module2")
        perf_logger = get_performance_logger()

        logger1.info("Message from module 1")
        logger2.info("Message from module 2")
        perf_logger.info("Performance message")

    def test_force_reinit(self):
        """Test that force reinit works correctly."""
        setup_logging()

        # Should not reinitialize
        setup_logging()

        # Should reinitialize
        setup_logging(force_reinit=True)

    def test_fallback_logging(self):
        """Test that fallback logging works if setup fails."""
        # This test would require mocking the setup to fail
        # For now, just verify basic functionality
        logger = get_logger("test.fallback")
        logger.info("Fallback test message")
