from typing import Optional
import pathlib


def resolve_cache_root(
    cache_root: Optional[pathlib.Path],
    *directories: str
) -> pathlib.Path:
    """
    Resolve cache root.

    :param cache_root:
        The cache root. If None, use ~/.kgm
    :param directories:
        Additional directories inside the cache root which are created if necessary.

    :return:
        An absolute path to an existing directory.
    """
    # default cache root
    if cache_root is None:
        cache_root = pathlib.Path('~', '.kgm')
    # Ensure it is an absolute path
    cache_root = cache_root.expanduser().absolute()
    # Create sub-directories
    for directory in directories:
        cache_root = cache_root / directory
    # Ensure that cache_root is an existing directory
    cache_root.mkdir(parents=True, exist_ok=True)
    return cache_root