# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2023 SciCat Project (https://github.com/SciCatProject/scitacean)
"""Common utilities for file transfers."""

from typing import Optional, Union

from ..dataset import Dataset
from ..filesystem import RemotePath
from ..util.formatter import DatasetPathFormatter


def source_folder_for(
    dataset: Dataset, pattern: Optional[Union[str, RemotePath]]
) -> RemotePath:
    """Get or build the source folder for a dataset.

    Parameters
    ----------
    dataset:
        Build the source folder for this dataset.
    pattern:
        A string for constructing a source folder.
        Can have placeholders to be used by ``DatasetPathFormatter``.

    Returns
    -------
    :
        The source folder for the dataset.
    """
    if pattern is None:
        if dataset.source_folder is None:
            raise ValueError(
                "Cannot determine source_folder for dataset. "
                "Either the dataset's source_folder or the "
                "file transfer's source_folder must be set."
            )
        return dataset.source_folder

    return RemotePath(DatasetPathFormatter().format(str(pattern), dataset))
