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


def test_format_size():
    # We need to reach into core to test the 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():
    @monitor
    def sample_func():
        return "hello"

    assert sample_func() == "hello"


def test_threshold_logic(capsys):
    # capsys is a special pytest tool to "catch" what is printed to the console
    @monitor(threshold_sec=0.1)
    def slow_func():
        time.sleep(0.2)

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


def test_context_manager_capture():
    with audit_block("test_block") as audit:
        # Just ensure it runs without crashing
        x = 1 + 1
    assert audit.name == "test_block"


def test_log_file_creation():
    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)

    # --- THE FIX: Shutdown logging so Windows releases the file lock ---
    logger = logging.getLogger("ezaudit")
    for handler in logger.handlers[:]:
        handler.close()
        logger.removeHandler(handler)

    os.remove(log_name)  # Now Windows will allow it!
