import inspect
from functools import wraps

from urllib3.exceptions import MaxRetryError, ProtocolError

from taskingai import Config
from .exceptions import TaskingAIProtocolError


def validate_and_convert_errors(func):
    @wraps(func)
    def inner_func(*args, **kwargs):
        Config.validate()  # raises exceptions in case of invalid config
        try:
            return func(*args, **kwargs)
        except MaxRetryError as e:
            if isinstance(e.reason, ProtocolError):
                raise TaskingAIProtocolError(
                    f'Failed to connect to {e.url}. Please check your network connection and try again later.') from e
            else:
                raise
        except ProtocolError as e:
            raise TaskingAIProtocolError(f'Failed to connect. Please check your network connection and try again later.') from e

    # Override signature
    sig = inspect.signature(func)
    inner_func.__signature__ = sig
    return inner_func
