from typing import Union
import pathlib


def calculate_save_location(file: Union[pathlib.Path, str], source_directory: Union[pathlib.Path, str],
                            output_directory: Union[pathlib.Path, str], output_format: str = 'html') -> pathlib.Path:
    """
    Calculates where a file should be saved.
    :param file: A pathlib.Path object pointing to the file.
    :param source_directory: Where all the source files are stored.
    :param output_directory: Where all the HTML fies should be placed.
    :param output_format: The extension for the save location.
    :return:
    """
    if isinstance(file, str):
        file = pathlib.Path(file)
    if isinstance(source_directory, str):
        source_directory = pathlib.Path(source_directory)
    if isinstance(output_directory, str):
        output_directory = pathlib.Path(output_directory)

    directory: pathlib.Path = file.parent
    start, stop = directory.parts.index(source_directory.parts[0]), directory.parts.index(source_directory.parts[-1])
    pre: pathlib.Path = pathlib.Path(''.join(directory.parts[:start]))
    post: pathlib.Path = pathlib.Path(''.join(directory.parts[stop + 1:]))
    return pathlib.Path(pre).joinpath(output_directory).joinpath(post).joinpath(
        file.stem + '.' + output_format)