from importlib import import_module
from typing import Any, Callable

from app.config import settings


def _load_factory(path: str, default_attr: str = "create_provider") -> Callable[[Any], Any]:
    module_name, sep, attr = path.partition(":")
    if not module_name:
        raise RuntimeError("provider path is empty")
    module = import_module(module_name)
    factory_name = attr if sep else default_attr
    factory = getattr(module, factory_name, None)
    if not callable(factory):
        raise RuntimeError(f"provider factory not found: {path}")
    return factory


def create_email_provider(config: Any):
    path = getattr(config, "EMAIL_PROVIDER", settings.EMAIL_PROVIDER)
    return _load_factory(path)(config)


def create_sms_provider(config: Any):
    path = getattr(config, "SMS_PROVIDER", settings.SMS_PROVIDER)
    return _load_factory(path)(config)


def create_verification_provider(config: Any):
    path = getattr(
        config,
        "VERIFICATION_PROVIDER",
        "mode.verification.baidu_face_v3.provider:create_provider",
    )
    return _load_factory(path)(config)


def create_payment_provider(config: Any, provider_path: str):
    return _load_factory(provider_path)(config)
