#动态条件判断装饰器
# 通过 settings.py 控制是否启用 @cache_page，完全绕过缓存系统
from functools import wraps

from django.conf import settings
from django.views.decorators.cache import cache_page
from django_ratelimit.decorators import ratelimit


def conditional_cache_page(timeout):

    def decorator(view_func):
        # 关键条件判断：仅当 timeout > 0 时应用缓存装饰器
        return cache_page(timeout)(view_func) if timeout > 0 else view_func

    return decorator


# 动态限流装饰器
# 通过 settings.py 控制是否启用 @ratelimit，完全绕过缓存系统
def dynamic_ratelimit(rate=None, block=None, key=None):

    def decorator(view_func):
        # 优先使用装饰器参数，若未提供则使用 settings 默认值
        final_rate = rate if rate is not None else settings.RATELIMIT_RATE
        final_block = block if block is not None else settings.RATELIMIT_BLOCK
        final_key = key if key is not None else settings.RATELIMIT_RATE_KEY

        if settings.RATELIMIT_RATE and not settings.RATELIMIT_RATE == "0":
            # 启用限流：应用 ratelimit 装饰器
            wrapped_view = ratelimit(key=final_key,
                                     rate=final_rate,
                                     block=final_block)(view_func)
            return wraps(view_func)(wrapped_view)
        else:
            # 禁用限流：返回原始视图函数
            return view_func

    return decorator
