"""GraphQL extensions for query validation and security."""

from django.conf import settings
from strawberry.extensions import MaxTokensLimiter, QueryDepthLimiter

# Maximum query depth to prevent deeply nested queries
MAX_QUERY_DEPTH = 10

# Maximum number of tokens (approximate complexity measure)
MAX_TOKENS = 500


def get_extensions():
    """Get list of extensions based on environment."""
    extensions = [
        QueryDepthLimiter(max_depth=MAX_QUERY_DEPTH),
        MaxTokensLimiter(max_token_count=MAX_TOKENS),
    ]

    # Note: ApolloTracingExtension is async-only and doesn't work with
    # Django's sync WSGI server (runserver). It requires an ASGI server
    # like Uvicorn or Daphne. Disabled to avoid "no event loop" errors.

    return extensions


class IntrospectionDisabledExtension:
    """Extension to disable introspection in production."""

    def on_request_start(self):
        pass

    def on_request_end(self):
        pass

    def resolve(self, next_, root, info, *args, **kwargs):
        # Block introspection queries in production
        if not settings.DEBUG:
            if info.field_name in ("__schema", "__type"):
                raise Exception("Introspection is disabled in production")
        return next_(root, info, *args, **kwargs)
