import time
from django.utils import timezone


def get_client_ip(request):
    """
    获取客户端IP地址

    Args:
        request: Django HttpRequest对象

    Returns:
        str: 客户端IP地址
    """
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        # 处理多个代理的情况，取第一个IP
        ip = x_forwarded_for.split(',')[0].strip()
    else:
        ip = request.META.get('REMOTE_ADDR', '0.0.0.0')
    return ip


def format_duration(seconds):
    """
    格式化时间间隔

    Args:
        seconds (float): 秒数

    Returns:
        str: 格式化后的时间字符串
    """
    if seconds < 0.001:
        return f"{seconds * 1000000:.0f}µs"
    elif seconds < 1:
        return f"{seconds * 1000:.0f}ms"
    else:
        return f"{seconds:.3f}s"


def should_log_request(request):
    """
    判断是否应该记录该请求的日志

    Args:
        request: Django HttpRequest对象

    Returns:
        bool: 是否记录日志
    """
    # 排除静态文件请求
    excluded_paths = ['/static/', '/media/', '/favicon.ico']
    path = request.path

    for excluded_path in excluded_paths:
        if path.startswith(excluded_path):
            return False

    return True


class RequestLog:
    """请求日志数据类"""

    def __init__(self, method, path, status_code, duration, ip, user_agent):
        self.method = method
        self.path = path
        self.status_code = status_code
        self.duration = duration
        self.ip = ip
        self.user_agent = user_agent
        self.timestamp = timezone.now()

    def to_dict(self):
        """转换为字典格式"""
        return {
            'method': self.method,
            'path': self.path,
            'status_code': self.status_code,
            'duration': self.duration,
            'duration_formatted': format_duration(self.duration),
            'ip_address': self.ip,
            'user_agent': self.user_agent,
            'timestamp': self.timestamp.isoformat(),
        }

    def __str__(self):
        return (f"{self.timestamp.strftime('%Y-%m-%d %H:%M:%S')} "
                f"{self.method} {self.path} {self.status_code} "
                f"{format_duration(self.duration)}")