# file: integrations/grpc.py

"""
gRPC Instrumentation Module.

Uses gRPC's interceptor API to create trace spans for RPC calls.

# Example usage:
# # from grpc import insecure_channel
# from integrations.grpc import telemetry_interceptor

import grpc
# Impor interceptor yang sudah diinisialisasi oleh init_telemetry()
from your_library.integrations.grpc import telemetry_interceptor

# Buat channel seperti biasa
channel = grpc.insecure_channel('localhost:50051')

# Terapkan interceptor ke channel
if telemetry_interceptor:
    intercepted_channel = grpc.intercept_channel(channel, telemetry_interceptor)
else:
    intercepted_channel = channel # Fallback jika telemetri tidak aktif

# Gunakan channel yang sudah diinstrumentasi
stub = GreeterStub(intercepted_channel)
response = stub.SayHello(HelloRequest(name='you'))
"""

from ..apiTelemetry import logger, trace_span

_instrumented = False
telemetry_interceptor = None  # Variabel global untuk menyimpan instance


def instrument():
    """Initializes the gRPC interceptor. Does not perform monkey patching."""
    global _instrumented, telemetry_interceptor
    if _instrumented:
        return

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

    # NOTE: these are the REAL grpcio client-interceptor base classes.
    # (``grpc.UnaryClientInterceptor`` / ``grpc.StreamClientInterceptor`` do
    # not exist in grpcio and would raise AttributeError at import time.)
    class TelemetryInterceptor(
        grpc.UnaryUnaryClientInterceptor,
        grpc.UnaryStreamClientInterceptor,
        grpc.StreamUnaryClientInterceptor,
        grpc.StreamStreamClientInterceptor,
    ):  # type: ignore[attr-defined]
        """A gRPC client interceptor that wraps every RPC in a trace span.

        IMPORTANT: the span must wrap the ``continuation(...)`` call itself.
        An earlier version only marked a flag and returned, producing ~0ms
        spans that never actually timed the RPC.
        """

        @staticmethod
        def _span_name_and_attrs(client_call_details):
            # client_call_details.method is e.g. "/helloworld.Greeter/SayHello".
            return (
                f"gRPC {client_call_details.method}",
                {"rpc.system": "grpc", "rpc.method": client_call_details.method},
            )

        def intercept_unary_unary(self, continuation, client_call_details, request):
            name, attrs = self._span_name_and_attrs(client_call_details)
            with trace_span(name, attributes=attrs):
                return continuation(client_call_details, request)

        def intercept_unary_stream(self, continuation, client_call_details, request):
            name, attrs = self._span_name_and_attrs(client_call_details)
            with trace_span(name, attributes=attrs):
                # NOTE: for streaming responses the span closes when the
                # iterator is returned, not when it is fully consumed.
                return continuation(client_call_details, request)

        def intercept_stream_unary(
            self, continuation, client_call_details, request_iterator
        ):
            name, attrs = self._span_name_and_attrs(client_call_details)
            with trace_span(name, attributes=attrs):
                return continuation(client_call_details, request_iterator)

        def intercept_stream_stream(
            self, continuation, client_call_details, request_iterator
        ):
            name, attrs = self._span_name_and_attrs(client_call_details)
            with trace_span(name, attributes=attrs):
                return continuation(client_call_details, request_iterator)

    telemetry_interceptor = TelemetryInterceptor()
    _instrumented = True
    # logger.info("gRPC TelemetryInterceptor initialized. Apply it manually to your gRPC channels.")
