import time
from functools import wraps

from backend.utils.logging_utils import get_logger
from flask import g, request

logger = get_logger(__name__)


def log_http_request(f):
    """
    Decorator that logs HTTP method, path, query params, user, and execution time.
    """

    @wraps(f)
    def decorated_function(*args, **kwargs):
        start_time = time.time()

        # Get request details
        method = request.method
        path = request.path
        query_params = dict(request.args)

        # Log the incoming request
        logger.info(f"(START REQUEST) {method} {path}  | Params: {query_params}")

        try:
            # Execute the actual route handler
            response = f(*args, **kwargs)

            # Calculate execution time
            execution_time = time.time() - start_time

            # Determine status code
            status_code = response[1] if isinstance(response, tuple) else 200

            # Log the response
            logger.info(f"(END REQUEST) {method} {path} | Status: {status_code} | Time: {execution_time:.3f}s")

            return response

        except Exception as e:
            execution_time = time.time() - start_time
            logger.error(f"(REQUEST ERROR) {method} {path} | Time: {execution_time:.3f}s | Error: {str(e)}")
            raise

    return decorated_function
