import base64
from starlette.middleware.base import BaseHTTPMiddleware
from fastapi import Request
from starlette.responses import Response
from .context import trace_id_ctx
import logging

class RequestIdFilter(logging.Filter):
    def filter(self, record):
        record.trace_id = trace_id_ctx.get()
        return True

class LogRequestMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        # token = trace_id_ctx.set(trace_id)
        # print("dispatch....", trace_id)
        try:

            # 打印请求基础元数据
            # print("request.headers:", request.headers,"request url:", request.url)
            # 转换 headers 为普通字典
            headers = {k: v for k, v in request.headers.items()}
            _header_sw8 = headers.get("sw8")
            # print("test--sw8:", _header_sw8)
            trace_id = "null-given"
            if _header_sw8:
                sw8_split = _header_sw8.split("-")
                if len(sw8_split) >= 2:
                    try:
                        trace_id = base64.b64decode(sw8_split[1]).decode('utf-8')
                    except Exception:
                        trace_id = "invalid"


            trace_id_ctx.set(trace_id)
            response: Response = await call_next(request)

            return response

        except Exception as e:
            print(f"trace_id-{trace_id}--LogRequestMiddleware 执行异常: {str(e)}")
        finally:
            trace_id = "null-failed"
            trace_id_ctx.set(trace_id)
            # print("finally....")
