# file: integrations/graphql.py

"""
GraphQL Instrumentation Module.

Provides Middleware for Graphene and an Extension for Strawberry-GraphQL
to automatically trace the execution of individual resolvers.

### Cara Penggunaan (PENTING)
Berbeda dengan instrumentasi lain, instrumentasi GraphQL harus diterapkan secara manual saat Anda mendefinisikan Skema GraphQL Anda.

Untuk Pengguna Graphene
Anda perlu menambahkan GrapheneTelemetryMiddleware ke dalam daftar middleware saat membuat graphene.Schema.

Contoh:

# Di file tempat Anda membuat skema Graphene
import graphene
from your_library.integrations.graphql import GrapheneTelemetryMiddleware
from your_library.apiTelemetry import get_current_client

# Buat daftar middleware
middlewares = []
client = get_current_client()
if client and client.config.instrument_graphql:
    middlewares.append(GrapheneTelemetryMiddleware())

# SEBELUM:
# schema = graphene.Schema(query=Query)

# SESUDAH:
schema = graphene.Schema(query=Query, middleware=middlewares)
"""

from ..apiTelemetry import spans_var, trace_span

# --- Graphene Integration ---


class GrapheneTelemetryMiddleware:
    """
    A Graphene middleware to create a trace span for each resolver execution.
    """

    def resolve(self, next, root, info, **kwargs):
        # Only trace if a telemetry trace is active.
        if spans_var.get() is None:
            return next(root, info, **kwargs)

        # Construct a descriptive name for the span.
        parent_type_name = info.parent_type.name
        field_name = info.field_name
        span_name = f"GRAPHQL {parent_type_name}.{field_name}"

        attributes = {
            "graphql.field_name": field_name,
            "graphql.parent_type": parent_type_name,
            "graphql.path": ".".join(map(str, info.path)),
        }

        with trace_span(span_name, attributes=attributes):
            # Proceed with the original resolver execution.
            return next(root, info, **kwargs)


# --- Strawberry-GraphQL Integration ---

try:
    from strawberry.extensions import Extension  # type: ignore[import-not-found]

    class StrawberryTelemetryExtension(Extension):
        """
        A Strawberry extension to create a trace span for each resolver execution.
        """

        def on_resolve(self):
            # This is a generator-based hook.

            # Code before yield runs before the resolver.
            if spans_var.get() is not None:
                info = self.execution_context.info
                parent_type_name = info.parent_type.name
                field_name = info.field_name
                span_name = f"GRAPHQL {parent_type_name}.{field_name}"

                attributes = {
                    "graphql.field_name": field_name,
                    "graphql.parent_type": parent_type_name,
                    "graphql.path": ".".join(map(str, info.path.as_list())),
                }

                with trace_span(span_name, attributes=attributes):
                    # Yield to execute the original resolver.
                    yield
            else:
                # If no trace is active, just proceed without instrumentation.
                yield

            # Code after yield runs after the resolver.
            # The context manager already handles timing and recording.

except ImportError:
    # This allows the library to work even if strawberry is not installed.
    StrawberryTelemetryExtension = None  # type: ignore[assignment]
