import time
import logging

logger = logging.getLogger(__name__)


class RequestTimingMiddleware:
    """生产环境接口耗时中间件"""
    SLOW_THRESHOLD_MS = 1000  # 慢请求阈值，毫秒

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        start_time = time.time()
        response = self.get_response(request)
        duration_ms = (time.time() - start_time) * 1000

        # 获取客户端 IP（优先 X-Forwarded-For）
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0].strip()
        else:
            ip = request.META.get('REMOTE_ADDR', '')

        method = request.method
        path = request.get_full_path()
        status_code = getattr(response, 'status_code', '')

        # 日志信息
        log_msg = f"[API][{ip}] {method} {path} -> {status_code} took {duration_ms:.2f}ms"
        logger.info(log_msg)

        if duration_ms > self.SLOW_THRESHOLD_MS:
            logger.warning(f"[SLOW API] {log_msg}")

        return response
