# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

from typing import Any, Union

from erniebot.api_types import APIType, convert_str_to_api_type
from erniebot.types import ConfigDictType

from .aistudio import AIStudioBackend
from .base import EBBackend
from .bce import QianfanBackend, QianfanLegacyBackend, YinianBackend
from .custom import CustomBackend

__all__ = ["build_backend"]


def build_backend(api_type: Union[str, APIType], config_dict: ConfigDictType, **opts: Any) -> EBBackend:
    if isinstance(api_type, str):
        api_type = convert_str_to_api_type(api_type)
    if api_type is APIType.QIANFAN:
        return QianfanLegacyBackend(config_dict, **opts)
    elif api_type is APIType.YINIAN:
        return YinianBackend(config_dict, **opts)
    elif api_type is APIType.AISTUDIO:
        return AIStudioBackend(config_dict, **opts)
    elif api_type is APIType.QIANFAN_SFT:
        return QianfanBackend(config_dict, **opts)
    elif api_type is APIType.CUSTOM:
        return CustomBackend(config_dict, **opts)
    else:
        raise ValueError(f"Unrecoginzed API type: {api_type.name}")
