from pathlib import Path


def get_help_file(help_dir, cmd):
    """
    Gets most recently generated helptext for AFNI `cmd` in `help_dir`

    Parameters
    ----------
    help_dir : str
        Path to directory with AFNI help files
    cmd : str
        AFNI command for which to grab help file

    Returns
    -------
    fname : str
        Path to most recently generated help file
    """
    help_dir = Path(help_dir).resolve()
    help_fnames = sorted(help_dir.glob(cmd + '.????_??_??-??_??_??.help'))
    try:
        return help_fnames[-1]
    except IndexError:
        raise FileNotFoundError('Cannot find any valid help files for {} in {}'
                                .format(cmd, help_dir.as_posix()))