import logging

from opentelemetry import trace as trace_api

logger = logging.getLogger(__name__)


def int_to_hex(int_val: int, length: int):
    hex_val = hex(int_val)
    hex_val = hex_val[2:].zfill(length)
    return hex_val


def build_traceparent_header(span=None):
    """
    Builds a W3C-compliant traceparent header string from the provided span or the currently active span.

    The traceparent header is used for distributed tracing and follows the format:
    "version-trace-id-span-id-flags". This function extracts the necessary trace
    information from the span and formats it accordingly.

    Parameters
    ----------
    span : Optional[object]
        The span object to extract context from. If None, the current active span is used.

    Returns
    -------
    str
        The formatted traceparent header string, e.g.,
        "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01".

    If an error occurs during processing, the function logs the exception
    and returns `None`.

    Raises
    -------
    ValueError: If the span context is missing required attributes.
    Exception: Any other unexpected errors are logged and handled gracefully.
    """

    try:
        if span is None:
            span = trace_api.get_current_span()

        span_context = span.get_span_context()
        trace_id_hex = int_to_hex(span_context.trace_id, 32)
        span_id_hex = int_to_hex(span_context.span_id, 16)

        return f"00-{trace_id_hex}-{span_id_hex}-01"
    except Exception as e:
        logger.error("Failed to build traceparent header: %s", str(e), exc_info=True)
        return None
