from pathlib import Path
from typing import Optional


def ensure_extension(path: Path, extension: Optional[str]) -> Path:
    """Returns path and appends extension if it is missing

    Raises an error if the extension does not match
    """
    if extension is None:
        return path
    assert extension.startswith(".")
    suffixes = path.suffixes
    if suffixes:
        if "".join(suffixes) == extension:
            return path
        else:
            raise ValueError(f"Unexpected extension: expected {extension}, got {path}")
    else:
        return Path(str(path) + extension)