import logging
from typing import List

from edpconfigprovider import ConfigProvider
from edpconfigprovider.exceptions import NoConfigurationException

logger = logging.getLogger(__name__)


class FallbackConfigProvider(ConfigProvider):
    def __init__(self, providers: List[ConfigProvider]) -> None:
        if not providers:
            raise ValueError("FallbackConfigProvider requires at least one provider")
        self._providers = providers

    def get_configuration(self) -> dict:
        last_exception = NoConfigurationException("fallback")
        for i, provider in enumerate(self._providers):
            try:
                return provider.get_configuration()
            except NoConfigurationException as e:
                logger.warning(
                    "Provider %s (%d/%d) failed: %s. Trying next.",
                    type(provider).__name__, i + 1, len(self._providers), e
                )
                last_exception = e

        raise last_exception
