"""
COPYRIGHT STATEMENT:

ChromaQuant – A quantification software for complex gas chromatographic data

Copyright (c) 2026, by Julia Hancock
              Affiliation: Dr. Julie Elaine Rorrer
              URL: https://www.rorrerlab.com/

License: BSD 3-Clause License

---

FUNCTIONS FOR HANDLING LOGGING AND ERRORS

Julia Hancock
Started 1-7-2026

"""

import logging
from functools import wraps
from collections.abc import Callable
from typing import Any


# Function to format logger
def setup_logger(logger: logging.Logger) -> logging.Logger:

    # Check if logger has handlers, clear if so
    if (logger.hasHandlers()):
        logger.handlers.clear

    # Add a handler for the console
    console_handler = logging.StreamHandler()
    logger.addHandler(console_handler)

    # Create a formatter object
    formatter = logging.Formatter(
                "{asctime} - [{name:^8s}][{levelname:^8s}] {message}",
                style='{',
                datefmt='%Y-%m-%d %H:%M')

    # Set the console handler's format using the new formatter
    console_handler.setFormatter(formatter)

    # Set logger level - NOTE: Change before commit if debugging
    logger.setLevel(logging.INFO)

    return logger


# Function that sets up a decorator to log errors while handling them
def setup_error_logging(logger: logging.Logger) -> \
   Callable[[Callable[..., Any]], Callable[..., Any]]:

    # Decorator to log and handle errors
    def error_logging(f: Callable[..., Any]) -> Callable[..., Any]:

        # Define decorated function (wrapper)
        @wraps(f)
        def decorated_func(*args: Any, **kwargs: Any) -> Callable[..., Any]:

            # Try to get the function's result
            try:
                result = f(*args, **kwargs)
                return result

            # Log errors if they occur
            except Exception as e:
                logger.error(e)
                raise

        return decorated_func

    return error_logging
