# Copyright 2026 4f4d
# Licensed under the Apache License, Version 2.0

"""Tests for f1radio.cache."""

import json
import pytest

from f1radio.cache import CacheManager, _sanitize_name


class TestSanitizeName:
    def test_basic(self):
        assert _sanitize_name("Italian Grand Prix") == "italian_grand_prix"

    def test_special_chars(self):
        assert _sanitize_name("Spa-Francorchamps") == "spa-francorchamps"

    def test_numbers(self):
        assert _sanitize_name("Race 2024") == "race_2024"


class TestCacheManager:
    def test_is_cached_false(self, tmp_path):
        from f1radio import cache
        original = cache._cache_dir
        cache._cache_dir = tmp_path

        mgr = CacheManager()
        assert mgr.is_cached(2023, "Monza", "Race") is False

        cache._cache_dir = original

    def test_save_and_load_context(self, tmp_path):
        from f1radio import cache
        original = cache._cache_dir
        cache._cache_dir = tmp_path

        mgr = CacheManager()
        data = [{"key": "value"}, {"key": "value2"}]
        mgr.save_context(2023, "Monza", "Race", "position", data)

        loaded = mgr.load_context(2023, "Monza", "Race", "position")
        assert loaded == data

        cache._cache_dir = original

    def test_save_and_load_metadata(self, tmp_path):
        from f1radio import cache
        original = cache._cache_dir
        cache._cache_dir = tmp_path

        mgr = CacheManager()
        meta = {"session_key": 9158, "year": 2023}
        mgr.save_metadata(2023, "Monza", "Race", meta)

        loaded = mgr.load_metadata(2023, "Monza", "Race")
        assert loaded["session_key"] == 9158
        assert mgr.is_cached(2023, "Monza", "Race") is True

        cache._cache_dir = original

    def test_clear_cache(self, tmp_path):
        from f1radio import cache
        original = cache._cache_dir
        cache._cache_dir = tmp_path

        mgr = CacheManager()
        mgr.save_context(2023, "Monza", "Race", "test", [{"a": 1}])
        mgr.save_metadata(2023, "Monza", "Race", {"key": 1})

        count = mgr.clear_cache()
        assert count >= 1
        assert mgr.is_cached(2023, "Monza", "Race") is False

        cache._cache_dir = original

    def test_cache_info(self, tmp_path):
        from f1radio import cache
        original = cache._cache_dir
        cache._cache_dir = tmp_path

        mgr = CacheManager()
        mgr.save_metadata(2023, "Monza", "Race", {"key": 1})

        info = mgr.cache_info()
        assert "sessions" in info
        assert "total_size_mb" in info
        assert len(info["sessions"]) >= 1

        cache._cache_dir = original

    def test_load_context_missing(self, tmp_path):
        from f1radio import cache
        original = cache._cache_dir
        cache._cache_dir = tmp_path

        mgr = CacheManager()
        result = mgr.load_context(2023, "Nonexistent", "Race", "position")
        assert result is None

        cache._cache_dir = original
