"""
Tests for the EZ-Audit core functionality.
"""

import logging
import os
import time
from ezaudit import monitor, audit_block, configure


def test_format_size() -> None:
    """Test the byte formatting helper function."""
    from ezaudit.core import format_size
    assert format_size(500) == "500.00B"
    assert format_size(2048) == "2.00KB"
    assert format_size(1024 * 1024) == "1.00MB"


def test_monitor_decorator() -> None:
    """Verify that the decorator returns the correct value."""
    @monitor
    def sample_func():
        return "hello"
    assert sample_func() == "hello"


def test_threshold_logic(capsys) -> None:
    """Verify that the threshold warning prints to the console."""
    @monitor(threshold_sec=0.1)
    def slow_func():
        time.sleep(0.15)

    slow_func()
    captured = capsys.readouterr()
    assert "[THRESHOLD EXCEEDED]" in captured.out


def test_context_manager_capture() -> None:
    """Verify context manager metadata collection."""
    with audit_block("test_block") as audit:
        _ = 1 + 1  # Use underscore to avoid 'unused variable' warning
    assert audit.name == "test_block"


def test_log_file_creation() -> None:
    """Verify log file persistence and cleanup."""
    log_name = "test_run.log"
    if os.path.exists(log_name):
        os.remove(log_name)

    configure(log_file=log_name)

    @monitor
    def dummy():
        pass

    dummy()
    assert os.path.exists(log_name)

    # Shutdown logging to release file lock on Windows
    logger = logging.getLogger("ezaudit")
    for handler in logger.handlers[:]:
        handler.close()
        logger.removeHandler(handler)

    os.remove(log_name)
