import logging

from engine.core.models import Vendor
from engine.core.vendors import AbstractVendor
from evibes.utils.misc import create_object

logger = logging.getLogger(__name__)


def get_vendors_integrations(name: str | None = None) -> list[AbstractVendor]:
    vendors_integrations: list[AbstractVendor] = []

    vendors = Vendor.objects.filter(is_active=True, integration_path__isnull=False)
    if name:
        vendors = vendors.filter(name=name)

    for vendor in vendors:
        try:
            module_name, class_name = vendor.integration_path.rsplit(".", 1)
            vendors_integrations.append(create_object(module_name, class_name))
        except Exception as e:
            logger.warning(
                "Couldn't load integration %s for vendor %s: %s",
                vendor.integration_path,
                vendor.name,
                str(e),
            )

    return vendors_integrations
