# Copyright 2024 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""utils of importlib"""
import os
import importlib
import sys


def direct_mindformers_import(path: str, file="__init__.py"):
    """Imports mindformers directly

    Args:
        path (`str`): The path to the source file.
        file (`str`, optional): The file to join with the path. Defaults to "__init__.py".

    Returns:
        `ModuleType`: The resulting imported module
    """
    name = "mindformers"
    location = os.path.join(path, file)
    spec = importlib.util.spec_from_file_location(name, location, submodule_search_locations=[path])
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    module = sys.modules.get(name, None)
    return module


def _is_package_available(pkg_name: str) -> bool:
    """_is_package_available"""
    # Check we're not importing a "pkg_name" directory somewhere but the actual library by trying to grab the version
    return pkg_name in sys.modules


def is_tokenizers_available():
    return _is_package_available("tokenizers")


def is_sentencepiece_available():
    return _is_package_available("sentencepiece")
