"""Tests for sondeo timer profiling."""

from sondeo.profiler.logging import clear_events
from sondeo.profiler.timer import clear_results, get_results, profile, timer


def test_timer_context_manager():
    clear_results()
    clear_events()

    with timer("test block") as t:
        _ = sum(range(10_000))

    assert t.elapsed_ms > 0
    assert t.name == "test block"

    results = get_results()
    assert len(results) == 1
    assert results[0].name == "test block"
    assert results[0].correlation_id is not None
    clear_results()
    clear_events()


def test_profile_decorator():
    clear_results()
    clear_events()

    @profile
    def slow_function():
        return sum(range(100_000))

    result = slow_function()
    assert result == sum(range(100_000))

    results = get_results()
    assert len(results) == 1
    assert "slow_function" in results[0].name
    assert results[0].elapsed_ms > 0
    assert results[0].correlation_id is not None
    clear_results()
    clear_events()


def test_profile_with_args():
    clear_results()
    clear_events()

    @profile(sort_by="tottime", top_n=5)
    def compute():
        return [i**2 for i in range(10_000)]

    compute()

    results = get_results()
    assert len(results) == 1
    clear_results()
    clear_events()
