
from logging import getLogger
from os import environ

from pkg_resources import iter_entry_points

from opentelemetry.instrumentation.dependencies import (
    get_dist_dependency_conflicts,
)
from opentelemetry.instrumentation.distro import BaseDistro, DefaultDistro
from opentelemetry.instrumentation.environment_variables import (
    OTEL_PYTHON_DISABLED_INSTRUMENTATIONS,
)
from opentelemetry.instrumentation.version import __version__


logger = getLogger(__name__)


# def _load_distros() -> BaseDistro:
#     for entry_point in iter_entry_points("opentelemetry_distro"):
#         try:
#             distro = entry_point.load()()
#             if not isinstance(distro, BaseDistro):
#                 logger.debug(
#                     "%s is not an OpenTelemetry Distro. Skipping",
#                     entry_point.name,
#                 )
#                 continue
#             logger.debug(
#                 "Distribution %s will be configured", entry_point.name
#             )
#             return distro
#         except Exception as exc:  # pylint: disable=broad-except
#             logger.exception(
#                 "Distribution %s configuration failed", entry_point.name
#             )
#             raise exc
#     return DefaultDistro()


def _load_instrumentors():
    package_to_exclude = environ.get(OTEL_PYTHON_DISABLED_INSTRUMENTATIONS, [])
    if isinstance(package_to_exclude, str):
        package_to_exclude = package_to_exclude.split(",")
        # to handle users entering "requests , flask" or "requests, flask" with spaces
        package_to_exclude = [x.strip() for x in package_to_exclude]

    for entry_point in iter_entry_points("opentelemetry_pre_instrument"):
        entry_point.load()()

    for entry_point in iter_entry_points("opentelemetry_instrumentor"):
        if entry_point.name in package_to_exclude:
            logger.debug(
                "Instrumentation skipped for library %s", entry_point.name
            )
            continue

        try:
            conflict = get_dist_dependency_conflicts(entry_point.dist)
            if conflict:
                logger.debug(
                    "Skipping instrumentation %s: %s",
                    entry_point.name,
                    conflict,
                )
                continue

            # tell instrumentation to not run dep checks again as we already did it above
            instrumentor = entry_point.load()
            instrumentor().instrument()
            # distro.load_instrumentor(entry_point, skip_dep_check=True)
            # logger.debug("Instrumented %s", entry_point.name)
        except Exception as exc:  # pylint: disable=broad-except
            logger.exception("Instrumenting of %s failed", entry_point.name)
            raise exc

    for entry_point in iter_entry_points("opentelemetry_post_instrument"):
        entry_point.load()()


def _load_configurators():
    configured = None
    for entry_point in iter_entry_points("opentelemetry_configurator"):
        if configured is not None:
            logger.warning(
                "Configuration of %s not loaded, %s already loaded",
                entry_point.name,
                configured,
            )
            continue
        try:
            entry_point.load()().configure(auto_instrumentation_version=__version__)  # type: ignore
            configured = entry_point.name
        except Exception as exc:  # pylint: disable=broad-except
            logger.exception("Configuration of %s failed", entry_point.name)
            raise exc



def initialize():
    # distro = _load_distros()
    # distro.configure()
    _load_configurators()
    _load_instrumentors()

# Notes:
## Install opentelemetry stuff
## Use this to configure in heimdall.start()