"""
Determines whether this device is cpu or gpu.
"""

import torch  # pylint: disable=import-outside-toplevel


def get_computing_device() -> str:
    """Get the computing device."""
    try:
        if torch.cuda.is_available():
            return "cuda"
        return "cpu"
    except ImportError:
        return "cpu"


def _sanitize_filepath(folder_name: str) -> str:
    """Sanitize a folder name."""
    return "".join([c for c in folder_name if c.isalnum() or c in ["-", "_"]])


def sanitize_path(path: str) -> str:
    """Sanitizes a path."""
    # Generated by ai.
    out = (
        str(_sanitize_filepath(path))  # type: ignore
        .replace(" ", "_")
        .replace("/", "_")
        .replace("\\", "_")
        .replace(".", "_")
        .replace("-", "_")
        .replace(",", "_")
        .replace(":", "_")
        .replace(";", "_")
        .replace("(", "_")
        .replace(")", "_")
        .replace("[", "_")
        .replace("]", "_")
        .replace("{", "_")
        .replace("}", "_")
        .replace("<", "_")
        .replace(">", "_")
        .replace("?", "_")
        .replace("!", "_")
        .replace("@", "_")
        .replace("#", "_")
        .replace("$", "_")
        .replace("%", "_")
        .replace("^", "_")
        .replace("&", "_")
        .replace("*", "_")
        .replace("+", "_")
        .replace("=", "_")
        .replace("|", "_")
        .replace("~", "_")
        .replace("`", "_")
        .replace("'", "_")
        .replace('"', "_")
        .replace(" ", "_")
        .replace("\t", "_")
        .replace("\n", "_")
        .replace("\r", "_")
    )
    while len(out) > 4 and out[-1] == "_":
        out = out[:-1]
    while len(out) > 4 and "__" in out:
        out = out.replace("__", "_")
    return out


def chop_double_extension(path_name):
    """takes in a path like out.mp3.txt and returns out.mp3"""
    # Split the path name on "."
    parts = path_name.split(".")
    # If there are fewer than two parts, return the original path name
    if len(parts) < 2:
        return path_name
    # Otherwise, return the second-to-last part followed by the last part
    return parts[-2] + "." + parts[-1]
