import os

import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration

from ocyan.core.plugins import OcyanPluginConfig


def _get_fender_config():
    try:
        from ocyan.core.fender import config
    except Exception:  # pragma: no cover - legacy runtime dependency can be absent
        return None
    return config


def get_dsn():
    if not os.environ.get("DJANGO_SETTINGS_MODULE", "").endswith(".base"):
        config = _get_fender_config()
        if config is None:
            return None
        try:
            return config.get("sentry logging", "dsn_secret")
        except Exception:  # pragma: no cover - fail closed on broken config backend
            return None
    return None


def get_dns():  # pragma: no cover - backwards compatibility
    return get_dsn()


def initialize_sentry():
    dsn = get_dsn()
    if not dsn:
        return False

    sentry_sdk.init(  # pylint:disable=abstract-class-instantiated
        dsn=dsn,
        integrations=[DjangoIntegration()],
        send_default_pii=True,
        traces_sample_rate=0,
        sample_rate=1.0,
    )
    return True


DSN_SECRET = get_dsn()


class SentryLoggingConfig(OcyanPluginConfig):
    def contribute_to_installed_apps(self, installed_apps):
        installed_apps.ocyan.append(
            "ocyan.plugin.sentry_logging.apps.OcyanPluginSentryLoggingAppConfig"
        )
        return installed_apps

    def contribute_to_settings(self, settings):
        initialize_sentry()
        return settings
