import time
from unittest.mock import patch

from mcsci_hub.cache import TTLCache


def test_cache_ttl_expiration():
    cache = TTLCache(max_size=100, ttl=1)
    cache.set("key", "value")
    assert cache.get("key") == "value"

    # Mock time to advance past TTL
    with patch("mcsci_hub.cache.time") as mock_time:
        mock_time.monotonic.return_value = time.monotonic() + 2
        assert cache.get("key") is None


def test_cache_lru_eviction():
    cache = TTLCache(max_size=2, ttl=3600)
    cache.set("a", 1)
    cache.set("b", 2)
    cache.set("c", 3)  # should evict "a"
    assert cache.get("a") is None
    assert cache.get("b") == 2
    assert cache.get("c") == 3


def test_cache_clear():
    cache = TTLCache(max_size=100, ttl=3600)
    cache.set("key", "value")
    assert len(cache) == 1
    cache.clear()
    assert len(cache) == 0


def test_cache_update_existing():
    cache = TTLCache(max_size=100, ttl=3600)
    cache.set("key", "old")
    cache.set("key", "new")
    assert cache.get("key") == "new"
    assert len(cache) == 1
