<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"
        integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
</html>
from typing import TYPE_CHECKING

from sentry_sdk.feature_flags import add_feature_flag
from sentry_sdk.integrations import DidNotEnable, Integration

try:
    import ldclient
    from ldclient.hook import Hook, Metadata

    if TYPE_CHECKING:
        from typing import Any

        from ldclient import LDClient
        from ldclient.evaluation import EvaluationDetail
        from ldclient.hook import EvaluationSeriesContext
except ImportError:
    raise DidNotEnable("LaunchDarkly is not installed")


class LaunchDarklyIntegration(Integration):
    identifier = "launchdarkly"

    def __init__(self, ld_client: "LDClient | None" = None) -> None:
        """
        :param client: An initialized LDClient instance. If a client is not provided, this
            integration will attempt to use the shared global instance.
        """
        try:
            client = ld_client or ldclient.get()
        except Exception as exc:
            raise DidNotEnable("Error getting LaunchDarkly client. " + repr(exc))

        if not client.is_initialized():
            raise DidNotEnable("LaunchDarkly client is not initialized.")

        # Register the flag collection hook with the LD client.
        client.add_hook(LaunchDarklyHook())

    @staticmethod
    def setup_once() -> None:
        pass


class LaunchDarklyHook(Hook):
    @property
    def metadata(self) -> "Metadata":
        return Metadata(name="sentry-flag-auditor")

    def after_evaluation(
        self,
        series_context: "EvaluationSeriesContext",
        data: "dict[Any, Any]",
        detail: "EvaluationDetail",
    ) -> "dict[Any, Any]":
        if isinstance(detail.value, bool):
            add_feature_flag(series_context.key, detail.value)

        return data

    def before_evaluation(
        self, series_context: "EvaluationSeriesContext", data: "dict[Any, Any]"
    ) -> "dict[Any, Any]":
        return data  # No-op.
