#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
请求日志中间件模块
提供请求日志记录功能
"""

import time
import traceback
from fastapi import Request
from fastapi.responses import JSONResponse

from utils.logger import get_logger
from routes.common_api import format_response

# 设置日志
logger = get_logger("middleware.request_logger")

async def log_requests(request: Request, call_next):
    """
    记录请求日志的中间件
    
    Args:
        request: 请求对象
        call_next: 下一个中间件或路由处理函数
        
    Returns:
        响应对象
    """
    start_time = time.time()
    
    # 获取请求信息
    method = request.method
    url = request.url.path
    client_host = request.client.host if request.client else "unknown"
    
    # 记录请求
    logger.info(f"请求开始: {method} {url} 来自 {client_host}")
    
    try:
        # 处理请求
        response = await call_next(request)
        
        # 计算处理时间
        process_time = time.time() - start_time
        logger.info(f"请求完成: {method} {url} 状态码: {response.status_code} 耗时: {process_time:.4f}秒")
        
        return response
    except Exception as e:
        # 记录异常
        process_time = time.time() - start_time
        logger.error(f"请求异常: {method} {url} 耗时: {process_time:.4f}秒")
        logger.error(f"异常详情: {str(e)}")
        logger.error(traceback.format_exc())
        
        # 返回通用错误响应
        return JSONResponse(
            status_code=500,
            content=format_response(
                code=500,
                message="服务器内部错误，请联系管理员",
                data=None
            )
        )

def register_middleware(app):
    """
    注册请求日志中间件到FastAPI应用
    
    Args:
        app: FastAPI应用实例
    """
    app.middleware("http")(log_requests) 