import pathlib
from typing import Optional


def find_snapshot(snapshot_dir: pathlib.Path,
                  snapshot_prefix: str = '',
                  snapshot_root: Optional[pathlib.Path] = None):
    """ Find the snapshot directory

    :param Path snapshot_dir:
        The path to the snapshot directory or None to go fishing
    :param str snapshot_prefix:
        The model-specific snapshot prefix
    :param Path snapshot_root:
        The base directory where snapshots are stored
    :returns:
        The path to the snapshot directory or None if one can't be found
    """

    if snapshot_dir is None:
        return None

    snapshot_dir = pathlib.Path(snapshot_dir)
    if snapshot_dir.is_dir():
        return snapshot_dir

    if snapshot_root is None:
        return None

    snapshot_name = snapshot_dir.name.strip('-')

    # Try adding a prefix to things
    for prefix in ('', snapshot_prefix, 'snapshot-' + snapshot_prefix):
        if prefix != '':
            prefix += '-'
        try_dir = snapshot_root / (prefix + snapshot_name)
        if try_dir.is_dir():
            return try_dir
    return None