import logging
from typing import Union
from pathlib import Path
import warnings


def add_logging_handler(
    logger: logging.Logger, logging_file_path: Union[str, Path]
) -> logging.FileHandler:
    """Add a logging file-handler to the logger.

    Parameters
    ----------
    logger : logging.Logger
        The logger.
    logging_file_path : Union[str, Path]
        The file path for the file handler.

    Returns
    -------
    logging.FileHandler
        The file-handler that is added to the given logger.

    """
    if not isinstance(logging_file_path, Path):
        logging_file_path = Path(logging_file_path)
    if logging_file_path.exists():
        warnings.warn(
            f"Logging file ({logging_file_path}) already exists. "
            f"This file will be overwritten!",
            RuntimeWarning,
        )
        # Clear the file
        #  -> because same FileHandler is used when calling this method twice
        open(logging_file_path, "w").close()
    f_handler = logging.FileHandler(logging_file_path, mode="w")
    f_handler.setFormatter(
        logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    )
    f_handler.setLevel(logging.INFO)
    logger.addHandler(f_handler)
    return f_handler