def _build_and_get_enum(
    store, var_name: str, dtype: np.dtype, enum_name: str, enum_dict: dict[str, int]
) -> ncEnumType | h5EnumType:
    """
    Add or get the netCDF4 Enum based on the dtype in encoding.
    The return type should be ``netCDF4.EnumType``,
    but we avoid importing netCDF4 globally for performances.
    """
    if enum_name not in store.ds.enumtypes:
        create_func = (
            store.ds.createEnumType
            if isinstance(store, NetCDF4DataStore)
            else store.ds.create_enumtype
        )
        return create_func(
            dtype,
            enum_name,
            enum_dict,
        )
    datatype = store.ds.enumtypes[enum_name]
    if datatype.enum_dict != enum_dict:
        error_msg = (
            f"Cannot save variable `{var_name}` because an enum"
            f" `{enum_name}` already exists in the Dataset but has"
            " a different definition. To fix this error, make sure"
            " all variables have a uniquely named enum in their"
            " `encoding['dtype'].metadata` or, if they should share"
            " the same enum type, make sure the enums are identical."
        )
        raise ValueError(error_msg)
    return datatype

    Add or get the netCDF4 Enum based on the dtype in encoding.
    The return type should be ``netCDF4.EnumType``,
    but we avoid importing netCDF4 globally for performances.
    
xarray/backends/netCDF4_.py