from pathlib import Path
from datetime import datetime
import shutil


def check_and_backup(filepath):
    """ Checks if a file exists at filepath and creates a timestamped backup of the file

        Args:
            filepath (str, pathlib.Path): Path to file
        Returns:
            pathlib.Path: Filepath
    """
    filepath = Path(filepath)

    if filepath.exists():
        filename = filepath.stem
        extension = filepath.suffix

        backup_filename = f"{filename}-{datetime.now().strftime('%Y%m%d-%H%M%S')}"

        backup_filepath = filepath.parent.joinpath(backup_filename).with_suffix(
            extension
        )

        print(
            f"Creating backup of previous version of {filepath.name} at {backup_filepath}"
        )

        shutil.copy(filepath, backup_filepath)
    else:
        print(f"{filepath.name} written")

    return filepath