from pathlib import Path
from typing import Optional


def check_for_tif_file(filepath: Path, prefix: str) -> Optional[Path]:
    """
    Returns a filepath if one exists, else returns None. This is useful
    because sometimes, Earth Engine exports files with characters added
    to the end of the filename, e.g. {intended_filename}{-more stuff}.tif
    """
    if (filepath / f"{prefix}.tif").exists():
        return filepath / f"{prefix}.tif"

    files_with_prefix = list(filepath.glob(f"{prefix}-*.tif"))
    if len(files_with_prefix) == 1:
        return files_with_prefix[0]
    elif len(files_with_prefix) == 0:
        return None
    elif len(files_with_prefix) > 1:
        print(f"Multiple files with prefix for {filepath /  prefix}.tif")
        return None