""" /lib/utils.py """

import time
from functools import wraps

from flask import jsonify
from flask import request

from lib.logger import logset

log = logset("PIAPP")
log.propagate = False


def handle_routes(f):
    """Decorator for wrapping endpoints for consistency"""

    @wraps(f)
    def wrapper(*args, **kwargs):
        start_time = time.time()  # Record the start time
        log.info(f"Accessing endpoint: {request.path} [Method: {request.method}]")
        try:
            # Call the actual endpoint function
            response = f(*args, **kwargs)
            return response
        except Exception as e:  # pylint: disable=broad-exception-caught
            # Log the exception with stack trace
            log.error(f"Exception in endpoint {request.path}: {str(e)}", exc_info=True)
            # Return JSON error response
            return jsonify({"error": "An unexpected error occurred", "details": str(e)}), 500
        finally:
            # Log the completion time
            elapsed_time = time.time() - start_time
            log.info(f"Completed endpoint: in {elapsed_time:.2f} seconds")

    return wrapper


# Apply the handler to all routes
def apply_handler(app):
    for rule in app.url_map.iter_rules():
        # Skip special endpoint handlers like static files
        if rule.endpoint == "static":
            continue

        # Get the original view function
        view_func = app.view_functions[rule.endpoint]

        # Replace it with the wrapped version
        app.view_functions[rule.endpoint] = handle_routes(view_func)
