# 工具方法
from django.conf import settings


def make_key(base: str, version: int = 1) -> str:
    """生成带版本控制的缓存键"""
    return f"{settings.CACHE_KEY_PREFIX}:{base}_v{version}"


class CacheMetrics:
    """实时监控仪表板"""
    _stats = {}

    @classmethod
    def record_hit(cls, layer: str):
        cls._stats.setdefault(layer, {'hits': 0, 'misses': 0})
        cls._stats[layer]['hits'] += 1

    @classmethod
    def record_miss(cls, layer: str):
        cls._stats.setdefault(layer, {'hits': 0, 'misses': 0})
        cls._stats[layer]['misses'] += 1

    @classmethod
    def get_report(cls):
        return {
            layer: {
                'hit_rate':
                data['hits'] / (data['hits'] + data['misses']) if
                (data['hits'] + data['misses']) > 0 else 0
            }
            for layer, data in cls._stats.items()
        }
