import time
import json
from django.utils import timezone
from .utils import get_client_ip, format_duration


class BruceRequestsLoggerMiddleware:
    """
    Bruce Django Requests Logger 中间件
    记录每个请求的详细信息并输出到控制台
    """

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

    def __call__(self, request):
        # 记录请求开始时间
        start_time = time.time()

        # 处理请求
        response = self.get_response(request)

        # 计算处理时间
        duration = time.time() - start_time

        # 创建日志条目
        log_entry = self._create_log_entry(request, response, duration)

        # 输出日志
        self._log_request(log_entry)

        # 添加响应头
        response['X-Request-Duration'] = format_duration(duration)

        return response

    def _create_log_entry(self, request, response, duration):
        """创建请求日志条目"""
        return {
            'timestamp': timezone.now().isoformat(),
            'method': request.method,
            'path': request.path,
            'query_string': request.META.get('QUERY_STRING', ''),
            'status_code': response.status_code,
            'duration': duration,
            'duration_formatted': format_duration(duration),
            'user_agent': request.META.get('HTTP_USER_AGENT', ''),
            'ip_address': get_client_ip(request),
            'content_type': response.get('Content-Type', ''),
            'content_length': response.get('Content-Length', ''),
        }

    def _log_request(self, log_entry):
        """记录请求日志"""
        log_output = json.dumps(log_entry, ensure_ascii=False, indent=2)
        print(f"[BRUCE_REQUESTS_LOGGER] {log_output}")