import pathlib
from typing import Union
from typing import Set
from typing import Dict
from pathlib import Path
import yaml


def get_item_yaml_values(
    item_path: pathlib.Path, keys: Union[str, Set[str]]
) -> Dict[str, Set[str]]:
    """
    Getting value from item.yaml requested field.

    :param item_path:       The path to the item.yaml file or the parent dir of the item.yaml.
    :param keys:            The fields names that contains the required values to collect,
                            also looks for the fields inside `spec` inside dict.

    :returns:               Set with all the values inside key.
    """
    if isinstance(keys, str):
        keys = {keys}
    values_dict = {}

    for key in keys:
        values_set = set()
        item_path = Path(item_path)
        if item_path.is_dir():
            item_path = item_path / "item.yaml"
        with open(item_path, "r") as f:
            item = yaml.full_load(f)
        if key in item:
            values = item.get(key, "")
        elif "spec" in item and key in item["spec"]:
            values = item["spec"].get(key, "") or ""
        else:
            values = ""

        if values:
            if isinstance(values, list):
                values_set = set(values)
            else:
                values_set.add(values)
        values_dict[key] = values_set
    return values_dict