from django.core.cache.backends.base import BaseCache


class SmartCache(BaseCache):

    def __init__(self, server, params, *args, **kwargs):
        super().__init__(params)
        # 从配置的OPTIONS中获取参数
        options = params.get('OPTIONS', {})
        self.layers = [
            self.create_layer(alias) for alias in options.get('LAYERS', [])
        ]
        self.default_timeout = options.get('TIMEOUT', 300)
        self.jitter = options.get('JITTER', (0, 60))

    def create_layer(self, alias):
        """通过别名获取已配置的缓存后端实例 """
        from django.core.cache import caches
        return caches[alias]

    def create_layer(self, alias):
        from django.core.cache import caches
        return caches[alias]

    def get(self, key, default=None, version=None):
        # 保持与之前相同的智能查询逻辑
        for i, layer in enumerate(self.layers):
            if (value := layer.get(key)) is not None:
                self._backfill_upper(key, value, i)
                return value
        return default

    def _backfill_upper(self, key, value, hit_level):
        """回填上层缓存"""
        for layer in self.layers[:hit_level]:
            layer.set(key, value, self.get_backfill_timeout())

    def get_backfill_timeout(self):
        from random import randint
        return self.default_timeout + randint(*self.jitter)

    # 实现其他必须的方法
    def set(self, key, value, timeout=None, version=None):
        timeout = timeout or self.default_timeout
        for layer in self.layers:
            layer.set(key, value, timeout)

    def delete(self, key, version=None):
        for layer in self.layers:
            layer.delete(key)

    def has_key(self, key, version=None):
        return any(layer.has_key(key) for layer in self.layers)
