from typing import Union
import pathlib


def matching_clean_file(dirty_filename, clean_folder: Union[str, pathlib.Path])\
        -> pathlib.Path:
    """ Find matching clean filepath given dirty filename/path
    Args:
        dirty_filename (Union[str, pathlib.Path]): Name of the dirty file
        clean_folder   (Union[str,pathlib.path]):  The folder of clean files

    Returns:
        pathlib.Path: Path to the clean 
    """
    # Cast to Path immediately
    dirty_filename = pathlib.Path(dirty_filename)
    clean_folder = pathlib.Path(clean_folder)

    # Get first part of name, e.g. "/workspace/dirty/abc.n2.wav" -> "abc"
    name = dirty_filename.stem.split('.')[0]

    # Find wav file in clean folder matching
    clean_file = clean_folder.glob(f"{name}.wav")
    clean_file = list(clean_file)  # Convert to list from generator

    if len(clean_file) != 1:
        raise FileNotFoundError(
            f"Could not find single {name} in {clean_folder}")

    return clean_file[0]