# file: integrations/redis.py

"""
Redis Instrumentation Module.

This module uses monkey patching to automatically trace commands sent via
the 'redis-py' library, creating spans within an active telemetry trace.
"""

from ..apiTelemetry import logger, spans_var, trace_span

# Global flag to ensure patching is only applied once per process.
_instrumented = False


def instrument():
    """
    Applies monkey patching to the 'redis.client.Redis' class to wrap
    the `execute_command` method.
    """
    global _instrumented
    if _instrumented:
        return

    try:
        from redis.client import Redis  # type: ignore[import-not-found]
    except ImportError:
        logger.debug("'redis' library not found, skipping instrumentation.")
        return

    # Store a reference to the original method.
    original_execute_command = Redis.execute_command

    def instrumented_execute_command(self, *args, **kwargs):
        """
        A wrapper around the original `execute_command` that creates a trace span.
        """
        # Do not trace if there is no active trace context.
        if spans_var.get() is None:
            return original_execute_command(self, *args, **kwargs)

        # The command is the first argument (e.g., 'GET', 'SET').
        command = args[0] if args else "UNKNOWN"
        span_name = f"REDIS {command.upper()}"

        # Prepare attributes for the span.
        attributes = {
            "db.system": "redis",
            "redis.command": command.upper(),
        }

        # The key is often the second argument.
        if len(args) > 1:
            # We convert the key to a string for safety.
            attributes["redis.key"] = str(args[1])

        # Use the trace_span context manager to automatically handle timing and appending.
        with trace_span(span_name, attributes=attributes):
            # Call the original redis method.
            return original_execute_command(self, *args, **kwargs)

    # Replace the original method with our instrumented version.
    Redis.execute_command = instrumented_execute_command

    _instrumented = True
