# -*- coding: utf-8 -*-
"""
工具函数
"""

import time
import random
import logging

# 配置日志
logger = logging.getLogger("qunkong")


def sleep(seconds: float):
    """
    等待指定秒数
    
    Args:
        seconds: 等待秒数
    """
    time.sleep(seconds)


def random_sleep(min_seconds: float, max_seconds: float):
    """
    随机等待
    
    Args:
        min_seconds: 最小等待秒数
        max_seconds: 最大等待秒数
    """
    time.sleep(random.uniform(min_seconds, max_seconds))


def random_offset(x: int, y: int, offset: int = 5) -> tuple:
    """
    给坐标添加随机偏移（防检测）
    
    Args:
        x: X坐标
        y: Y坐标
        offset: 偏移范围
    
    Returns:
        (new_x, new_y)
    """
    new_x = x + random.randint(-offset, offset)
    new_y = y + random.randint(-offset, offset)
    return new_x, new_y


def random_duration(base: int, variance: int = 50) -> int:
    """
    给时长添加随机变化（防检测）
    
    Args:
        base: 基础时长(毫秒)
        variance: 变化范围
    
    Returns:
        随机时长
    """
    return base + random.randint(-variance, variance)


def setup_logging(level: int = logging.INFO):
    """
    配置SDK日志
    
    Args:
        level: 日志级别
    """
    logging.basicConfig(
        level=level,
        format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    )


def retry(max_attempts: int = 3, delay: float = 1.0):
    """
    重试装饰器
    
    Args:
        max_attempts: 最大重试次数
        delay: 重试间隔(秒)
    """
    def decorator(func):
        def wrapper(*args, **kwargs):
            last_error = None
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    last_error = e
                    logger.warning(f"第{attempt + 1}次尝试失败: {e}")
                    if attempt < max_attempts - 1:
                        time.sleep(delay)
            raise last_error
        return wrapper
    return decorator
