from typing import Any, Dict

from opentelemetry import trace as trace_api
from opentelemetry.sdk.trace import Span


def add_span_attributes(span: Span, attributes: Dict[str, Any]):
    """
    Adds the specified attributes to the given span.

    This function sets key-value attributes to a tracing span.
    If the span is invalid (i.e., not actively traced), the function does nothing.

    Parameters
    ----------
    span : Span
        The span to which the attributes will be added.

    attributes : Dict[str, Any]
        A dictionary containing the attributes to be added to the span.
        Each key is the name of the attribute, and each value is the corresponding value to be set.

    Example
    -------
    .. code-block:: python

        from ytracing import add_span_attributes

        span = get_current_span()
        attributes = {"user_id": "12345", "request_id": "abcde"}
        add_span_attributes(span, attributes)
    """
    if span is not trace_api.INVALID_SPAN:
        for key, value in attributes.items():
            span.set_attribute(key, value)


def add_current_span_attributes(attributes: Dict[str, Any]):
    """
    Adds the specified attributes to the current span.

    This function retrieves the current active tracing span and assigns the given key-value attributes to it.
    It internally uses the `add_span_attributes` function to set these attributes.
    If there is no valid current span, the function does nothing.

    Parameters
    ----------
    attributes : Dict[str, Any]
        A dictionary containing the attributes to be added to the current span.
        Each key is the name of the attribute, and each value is the corresponding value to be set.

    Example
    -------
    .. code-block:: python

        from ytracing import add_current_span_attributes

        attributes = {"method": "GET", "status_code": 200}
        add_current_span_attributes(attributes)

    Notes
    -----
    It is a convenience wrapper around the `add_span_attributes` function,
    which allows you to avoid manually fetching the current span.

    """
    add_span_attributes(trace_api.get_current_span(), attributes)
