from re import findall
from pathlib import Path
from typing import Dict
from typing import Union


def _check_instrument(filepath: Path, gc_params: Dict, should_raise: bool = False) -> Union[str, None]:
    """Ensure we have the correct instrument or translate an instrument
    suffix to an instrument name.

    Args:
        instrument_suffix: Instrument suffix such as md
        should_raise: Should we raise if we can't find a valid instrument
        gc_params: GCWERKS parameters
    Returns:
        str: Instrument name
    """

    instrument: str = findall(r"[\w']+", str(filepath.name))[1].lower()
    try:
        if instrument in gc_params["instruments"]:
            return instrument
        else:
            try:
                instrument = gc_params["suffix_to_instrument"][instrument]
            except KeyError:
                if "medusa" in instrument:
                    instrument = "medusa"
                else:
                    raise KeyError(f"Invalid instrument {instrument}")
    except KeyError:
        if should_raise:
            raise
        else:
            return None

    return instrument