import time

import wrapt
from opentelemetry import trace
from opentelemetry.trace import get_current_span


def generic_trace(tracer_name):
    @wrapt.decorator
    def _traced_generic(func, instance, args, kwargs):
        with trace.get_tracer(tracer_name).start_as_current_span(func.__name__, kind=trace.SpanKind.CLIENT) as span:
            return func(*args, **kwargs)

    return _traced_generic


@wrapt.decorator
def _traced_time_generic(func, instance, args, kwargs):
    current_span = get_current_span()
    if current_span:
        start = time.perf_counter()
        response = func(*args, **kwargs)
        current_span.set_attribute("time_" + func.__name__, (time.perf_counter() - start) * 1e6)
    else:
        response = func(*args, **kwargs)

    return response
