from functools import wraps
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
import requests


def retry_on_network_error():
    """
    返回一个装饰器，用于类方法，自动从 self.retry 获取重试次数
    """
    def decorator(func):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            # 动态创建带 self.retry 的重试策略
            retrier = retry(
                stop=stop_after_attempt(self.retry),
                wait=wait_exponential(multiplier=1, min=1, max=10),
                retry=retry_if_exception_type((
                    requests.exceptions.Timeout,
                    requests.exceptions.ConnectionError,
                    requests.exceptions.HTTPError  # 可选：包含 5xx 等
                ))
            )
            # 应用重试到原函数
            return retrier(func)(self, * args, **kwargs)
        return wrapper
    return decorator