import time
from cachetiny.cache import cachetiny


def test_cache_returns_same_value():
    calls = {"count": 0}

    @cachetiny(ttl=10)
    def add(a, b):
        calls["count"] += 1
        return a + b

    result1 = add(1, 2)
    result2 = add(1, 2)

    assert result1 == 3
    assert result2 == 3
    assert calls["count"] == 1


def test_cache_expires_after_ttl():
    calls = {"count": 0}

    @cachetiny(ttl=1)
    def multiply(a, b):
        calls["count"] += 1
        return a * b

    result1 = multiply(2, 3)

    time.sleep(1.2)

    result2 = multiply(2, 3)

    assert result1 == 6
    assert result2 == 6
    assert calls["count"] == 2


def test_cache_different_args():
    calls = {"count": 0}

    @cachetiny(ttl=10)
    def subtract(a, b):
        calls["count"] += 1
        return a - b

    subtract(5, 3)
    subtract(10, 2)

    assert calls["count"] == 2


def test_cache_kwargs():
    calls = {"count": 0}

    @cachetiny(ttl=10)
    def greet(name="world"):
        calls["count"] += 1
        return f"hello {name}"

    greet(name="griffin")
    greet(name="griffin")

    assert calls["count"] == 1


def test_cache_logs_when_enabled(capfd):

    @cachetiny(ttl=10, log=True)
    def square(x):
        return x * x

    square(3)
    square(3)

    out, _ = capfd.readouterr()

    assert "COMPUTING" in out
    assert "USING CACHE" in out
