"""
Sentry service for error tracking and performance monitoring.
"""

import sentry_sdk
from sentry_sdk.integrations.asyncio import AsyncioIntegration
from sentry_sdk.integrations.fastapi import FastApiIntegration
from sentry_sdk.integrations.httpx import HttpxIntegration

from app.core.config import settings
from app.core.logging import get_logger

logger = get_logger("sentry")


class SentryService:
    """Service for managing Sentry configuration and initialization."""

    @staticmethod
    def init_sentry() -> None:
        """Initialize Sentry SDK with FastAPI integration."""
        if not settings.SENTRY_DSN:
            logger.warning("SENTRY_DSN not configured, skipping Sentry initialization")
            return

        try:
            sentry_sdk.init(
                dsn=settings.SENTRY_DSN,
                environment=settings.SENTRY_ENVIRONMENT,
                debug=settings.SENTRY_ENABLE_DEBUG,
                # Enable FastAPI integration
                integrations=[
                    FastApiIntegration(),
                    AsyncioIntegration(),
                    HttpxIntegration(),
                ],
                enable_logs=True,
                # Configure before_send to filter out certain errors
                before_send=SentryService._before_send,
                # Configure before_send_transaction to filter out certain transactions
                before_send_transaction=SentryService._before_send_transaction,
            )
            logger.info("✅ Sentry initialized successfully")
        except Exception as e:
            logger.error(f"❌ Failed to initialize Sentry: {e}")

    @staticmethod
    def _before_send(event, hint):
        """Filter events before sending to Sentry."""
        # Filter out certain types of errors if needed
        if "exc_info" in hint:
            exc_type, _exc_value, _exc_traceback = hint["exc_info"]
            # Example: Filter out specific exception types
            if exc_type.__name__ in ["ConnectionError", "TimeoutError"]:
                return None
        return event

    @staticmethod
    def _before_send_transaction(event):
        """Filter transactions before sending to Sentry."""
        # Filter out certain transactions if needed
        return event

    @staticmethod
    def capture_exception(exc: Exception, **kwargs) -> None:
        """Capture an exception in Sentry."""
        if settings.SENTRY_DSN:
            sentry_sdk.capture_exception(exc, **kwargs)

    @staticmethod
    def capture_message(message: str, level: str = "info", **kwargs) -> None:
        """Capture a message in Sentry."""
        if settings.SENTRY_DSN:
            sentry_sdk.capture_message(message, level=level, **kwargs)

    @staticmethod
    def set_user_context(user_id: str, email: str | None = None, **kwargs) -> None:
        """Set user context for Sentry events."""
        if settings.SENTRY_DSN:
            sentry_sdk.set_user({"id": user_id, "email": email, **kwargs})

    @staticmethod
    def set_tag(key: str, value: str) -> None:
        """Set a tag for Sentry events."""
        if settings.SENTRY_DSN:
            sentry_sdk.set_tag(key, value)

    @staticmethod
    def set_context(name: str, data: dict) -> None:
        """Set context data for Sentry events."""
        if settings.SENTRY_DSN:
            sentry_sdk.set_context(name, data)
