from typing import Optional  # noqa:F401

import ddtrace
import ddtrace.internal.runtime.runtime_metrics
from ddtrace.internal.telemetry import telemetry_writer


TELEMETRY_RUNTIMEMETRICS_ENABLED = "DD_RUNTIME_METRICS_ENABLED"


class _RuntimeMetricsStatus(type):
    @property
    def _enabled(_):
        # type: () -> bool
        """Runtime metrics enabled status."""
        return ddtrace.internal.runtime.runtime_metrics.RuntimeWorker.enabled


class RuntimeMetrics(metaclass=_RuntimeMetricsStatus):
    """
    Runtime metrics service API.

    This is normally started automatically by ``ddtrace-run`` when the
    ``DD_RUNTIME_METRICS_ENABLED`` variable is set.

    To start the service manually, invoke the ``enable`` static method::

        from ddtrace.runtime import RuntimeMetrics
        RuntimeMetrics.enable()
    """

    @staticmethod
    def enable(
        tracer: Optional[ddtrace.trace.Tracer] = None,
        dogstatsd_url: Optional[str] = None,
    ) -> None:
        """
        If the service has already been activated before, this method does
        nothing. Use ``disable`` to turn off the runtime metric collection
        service.

        :param tracer: The tracer instance to correlate with.
        """
        telemetry_writer.add_configuration(TELEMETRY_RUNTIMEMETRICS_ENABLED, True, origin="code")
        ddtrace.internal.runtime.runtime_metrics.RuntimeWorker.enable(tracer=tracer, dogstatsd_url=dogstatsd_url)

    @staticmethod
    def disable() -> None:
        """
        Disable the runtime metrics collection service.

        Once disabled, runtime metrics can be re-enabled by calling ``enable``
        again.
        """
        telemetry_writer.add_configuration(TELEMETRY_RUNTIMEMETRICS_ENABLED, False, origin="code")
        ddtrace.internal.runtime.runtime_metrics.RuntimeWorker.disable()


__all__ = ["RuntimeMetrics"]
