import os
from typing import Dict, Any
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

from .providers import create_provider


def _choose_provider() -> Any:
    """Choose and initialize the appropriate LLM provider with fallback logic."""
    try:
        return create_provider()
    except Exception as e:
        from .providers import EnhancedStubProvider
        import logging
        logging.warning(f"All providers failed to initialize: {e}. Using stub provider.")
        return EnhancedStubProvider()


class ProviderProxy:
    def __init__(self):
        self._provider = _choose_provider()

    def __getattr__(self, name):
        attr = getattr(self._provider, name)
        if callable(attr):
            def wrapper(*args, **kwargs):
                from .provider_utils import ProviderError, AuthenticationError, RateLimitError
                from .providers import EnhancedStubProvider
                import logging
                try:
                    return attr(*args, **kwargs)
                except (ProviderError, AuthenticationError, RateLimitError) as e:
                    logging.warning(f"Provider runtime error: {e}. Falling back to stub provider.")
                    self._provider = EnhancedStubProvider()
                    fallback_attr = getattr(self._provider, name)
                    return fallback_attr(*args, **kwargs)
            return wrapper
        return attr

llm = ProviderProxy()
