"""Sentry configuration - import early in main.py."""
from .. import settings
from .context import get_request_id, get_account_id, get_job_id


def _add_context_tags(event, hint):
    """Add request context as Sentry tags for correlation."""
    event.setdefault("tags", {})

    if request_id := get_request_id():
        event["tags"]["request_id"] = request_id
    if account_id := get_account_id():
        event["tags"]["account_id"] = account_id
    if job_id := get_job_id():
        event["tags"]["job_id"] = job_id

    return event


def _add_transaction_tags(event, hint):
    """Add context to performance traces too."""
    return _add_context_tags(event, hint)


def init_sentry():
    """Initialize Sentry. Call early in app startup."""
    try:
        import sentry_sdk
        from sentry_sdk.integrations.fastapi import FastApiIntegration
        from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
    except ImportError:
        return

    if not settings.SENTRY_DSN:
        return

    sentry_sdk.init(
        dsn=settings.SENTRY_DSN,
        environment=settings.ENVIRONMENT,
        traces_sample_rate=1.0,
        send_default_pii=False,
        integrations=[
            FastApiIntegration(),
            SqlalchemyIntegration(),
        ],
        before_send=_add_context_tags,
        before_send_transaction=_add_transaction_tags,
    )
