from .. import ConfigProvider
from ..builder import ProviderBuilder
from ._RedisCachingConfigProvider import RedisCachingConfigProvider, _DEFAULT_NAMESPACE


class CachingProviderBuilder(ProviderBuilder):
    """Wraps a ``ProviderBuilder`` so every provider it builds is cache-backed.

    Needed for the per-tenant dynamic path, where leaf providers are built lazily
    via ``build_provider(tenant_name=...)`` inside ``ByTenantDynamicConfigProvider``.
    Wrapping the builder ensures each tenant leaf is decorated with a
    :class:`RedisCachingConfigProvider` whose key already carries the tenant.
    """

    def __init__(
        self,
        inner_builder: ProviderBuilder,
        redis_client,
        ttl_seconds: int,
        namespace: str = _DEFAULT_NAMESPACE,
    ) -> None:
        self._inner_builder = inner_builder
        self._redis = redis_client
        self._ttl = ttl_seconds
        self._namespace = namespace

    def build_provider(self, **kwargs) -> ConfigProvider:
        inner = self._inner_builder.build_provider(**kwargs)
        return RedisCachingConfigProvider(
            inner=inner,
            redis_client=self._redis,
            ttl_seconds=self._ttl,
            namespace=self._namespace,
        )
