# apps/core/configs/ratelimit.py
# django-ratelimit全局限流设置
#   "RateLimitConfig": {
# "switch": false,
# "rate_key": "ip",
# "rate_link": "/",
# "global_rate": "None",
# "home_rate": "None",
# "category_rate": "None",
# "item_rate": "None",
# "tag_rate": "None"
#   }
try:
    # 注意：确保 GLOBAL_CONFIG 在此上下文中可访问，例如从主settings导入
    from django.conf import settings
    ratelimit_config = getattr(settings, 'GLOBAL_CONFIG', {}).get("RateLimitConfig", {})
    
    # 从GLOBAL_CONFIG中读取配置，失败则使用默认值
    RATELIMIT_ENABLE = ratelimit_config.get("switch", False)
    RATELIMIT_CACHE = 'default'  # 使用Django的默认缓存
    
    # 处理全局频率限制
    RATE_LIMIT_RATE = None if ratelimit_config.get("global_rate", '99999999999/s') == 'None' else ratelimit_config.get("global_rate", '99999999999/s')
    RATE_LIMIT_RATE_LINK = ratelimit_config.get("rate_link", '/')
    RATE_LIMIT_RATE_KEY = ratelimit_config.get("rate_key", 'ip')  # 通常使用'ip'或'user'
    RATE_LIMIT_BLOCK = True  # 超过限制时是否阻塞请求

    # 处理各个路径的频率限制
    RATE_LIMIT_HOME = None if ratelimit_config.get("home", '99999999999/s') == 'None' else ratelimit_config.get("home", '99999999999/s')
    RATE_LIMIT_CATEGORY = None if ratelimit_config.get("category_rate", '99999999999/s') == 'None' else ratelimit_config.get("category_rate", '99999999999/s')
    RATE_LIMIT_ITEM = None if ratelimit_config.get("item_rate", '99999999999/s') == 'None' else ratelimit_config.get("item_rate", '99999999999/s')
    RATE_LIMIT_TAG = None if ratelimit_config.get("tag_rate", '99999999999/s') == 'None' else ratelimit_config.get("tag_rate", '99999999999/s')

except Exception as e:
    # 如果读取配置出错，则禁用限流，并使用非常宽松的默认值
    print(f'ratelimit_config 读取错误: {e}')
    RATELIMIT_ENABLE = False
    RATELIMIT_CACHE = 'default'
    RATE_LIMIT_RATE = '99999999999/s'
    RATE_LIMIT_RATE_LINK = '/'
    RATE_LIMIT_RATE_KEY = 'ip'
    RATE_LIMIT_BLOCK = True
    # 其他路径限制也设为None或一个极高的值
    RATE_LIMIT_HOME = None
    RATE_LIMIT_CATEGORY = None
    RATE_LIMIT_ITEM = None
    RATE_LIMIT_TAG = None 

# 核心：将配置整合为一个字典，便于在主settings中导入和设置
# 注意：根据django-ratelimit文档，全局速率限制的键名应为 RATELIMIT_RATE，而非 RATE_LIMIT_RATE[2](@ref)
DJANGO_RATELIMIT_CONFIG = {
    'RATELIMIT_VIEW': 'apps.core.utils.beenLimited',  # 自定义限流触发后的视图[2](@ref)
    'RATELIMIT_ENABLE': RATELIMIT_ENABLE,
    'RATELIMIT_CACHE': RATELIMIT_CACHE,
    'RATELIMIT_RATE': RATE_LIMIT_RATE,  # 建议将此键名改为 RATELIMIT_RATE
    'RATE_LIMIT_RATE_LINK': RATE_LIMIT_RATE_LINK,
    'RATELIMIT_RATE_KEY': RATE_LIMIT_RATE_KEY,
    'RATELIMIT_BLOCK': RATE_LIMIT_BLOCK,  # 建议将此键名改为 RATELIMIT_BLOCK
    'RATE_LIMIT_HOME': RATE_LIMIT_HOME,
    'RATE_LIMIT_CATEGORY': RATE_LIMIT_CATEGORY,
    'RATE_LIMIT_ITEM': RATE_LIMIT_ITEM,
    'RATE_LIMIT_TAG': RATE_LIMIT_TAG,
}