# Copyright 2024 Klira AI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Error handling decorator for SDK operations."""

from __future__ import annotations

import functools
import logging
from typing import Any, Callable, TypeVar

logger = logging.getLogger(__name__)

F = TypeVar("F", bound=Callable[..., Any])


def handle_errors(
    fail_open: bool = True,
    default_return: Any = None,
) -> Callable[[F], F]:
    """Decorator for handling errors in SDK operations.

    Args:
        fail_open: If True, swallow exceptions and return default_return.
            If False, re-raise exceptions after logging.
        default_return: Value to return when fail_open=True and an error occurs.

    Returns:
        Decorated function.
    """

    def decorator(func: F) -> F:
        @functools.wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            try:
                return func(*args, **kwargs)
            except Exception as e:
                logger.error(
                    "Error in %s: %s",
                    func.__qualname__,
                    str(e),
                    exc_info=True,
                )
                if fail_open:
                    return default_return
                raise

        return wrapper  # type: ignore[return-value]

    return decorator
