import logging
import time
import json
from fastapi import FastAPI
from fastapi.middleware import Middleware
from pprint import pformat

logging.basicConfig(level=logging.DEBUG,  # Establecer el nivel de logging a DEBUG
                    format='%(levelname)s - %(asctime)s - %(message)s', # Formato del mensaje
                    handlers=[logging.StreamHandler()])  # Enviar los logs a la consola


class LoggerMiddleware(Middleware):

    def __init__(self, app: FastAPI, debug_level: int = logging.DEBUG):
        super().__init__(app)
        if not self.logger:
            self.logger = logging.getLogger(__name__)
            self.logger.setLevel(logging.DEBUG)

    async def dispatch(self, request, call_next):
        """
        Middleware function that logs information about incoming requests and their processing time.
        Args:
            request: The incoming request object.
            call_next: The next middleware or application handler.
        Returns:
            The response generated by the next middleware or application handler.
        Raises:
            Exception: If an error occurs during request processing.
        """

        try:
            header = dict(request.headers)
            body = await request.body()
            body = json.loads(body) if len(body) != 0 else ""
            start_time = time.time()
            response = await call_next(request)
            formatted_process_time = '{0:.2f}'.format((time.time() - start_time) * 1000)

            self.logger.debug(f"----------------------------------------")
            self.logger.debug(f"Request: {request.method} {request.url.path} :: Process Time: {formatted_process_time} ms")
            self.logger.debug(f"Headers: {pformat(header)}")
            self.logger.debug(f"Body: {pformat(body)}")
            self.logger.debug(f"----------------------------------------")

            return response

        except Exception as exc:
            self.logger.error(exc)
