"""
Test for logging file creation verification.

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

import logging
import os
import time

from mcard.config.config_constants import LOG_DIRECTORY, LOG_FILENAME
from mcard.config.logging import get_logger, setup_logging


def test_logging_file_creation():
    """Test that log file is created and messages are written."""
    # Ensure logging is initialized
    setup_logging(force_reinit=True)

    # Get the logger and set its level to DEBUG for testing
    logger = get_logger("mcard")
    logger.setLevel(logging.DEBUG)

    # Set handlers to DEBUG level
    for handler in logger.handlers:
        handler.setLevel(logging.DEBUG)

    # Create a unique test message to avoid false positives from previous test runs
    # Use INFO level since handlers might be configured at INFO level
    test_message = f"Testing logging file creation - {time.time()}"
    logger.info(test_message)

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

    # Allow time for the log message to be written
    time.sleep(0.5)

    # Get the expected log file path
    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)

    # Print debug info
    print(f"Looking for log file at: {log_file_path}")
    print(f"File exists: {os.path.exists(log_file_path)}")
    print(
        f"Logger level: {logger.level}, Handler levels: {[h.level for h in logger.handlers]}"
    )

    if os.path.exists(log_file_path):
        with open(log_file_path) as log_file:
            log_contents = log_file.read()
            print(f"Log contents (last 500 chars):\n{log_contents[-500:]}")
            assert (
                test_message in log_contents
            ), f"Test message '{test_message}' not found in log file"
    else:
        # Print directory contents for debugging
        log_dir = os.path.dirname(log_file_path)
        print(
            f"Directory contents ({log_dir}): {os.listdir(log_dir) if os.path.exists(log_dir) else 'Directory does not exist'}"
        )
        assert False, f"Log file was not created at {log_file_path}"
