"""Send each Sentry event to the project of the package that sent it.

See doc/sentry-package-routing.md.
"""
import json
import os
import time

from sentry_sdk import transport
from sentry_sdk.consts import DEFAULT_OPTIONS

from defence360agent.contracts.config import Packaging

CORE = "imunify-core"
# installed by the imunify-core package only, so a source tree or a
# container that runs the agent sends nothing
DSNS_FILE = os.path.join(Packaging.DATADIR, "sentry-projects.json")
_PACKAGES = {
    "defence360agent": CORE,
    "imav": "imunify-antivirus",
    "im360": "imunify360-firewall",
}
# the package that ships the entry point of this process
_declared = CORE


def declare_package(package):
    """Send the events that no package claims to *package*'s project.

    A script calls it once, with the package that ships the script.
    """
    global _declared
    if package not in _PACKAGES.values():
        raise ValueError("unknown package: %r" % (package,))
    _declared = package


def _names(event):
    yield event.get("logger")
    # innermost frame first: the caught exception, then its causes, then
    # the stack attached to an event without one
    for key in ("exception", "threads"):
        for value in reversed((event.get(key) or {}).get("values") or []):
            stacktrace = value.get("stacktrace") or {}
            for frame in reversed(stacktrace.get("frames") or []):
                yield frame.get("module")


def package_of(event):
    """The package whose project gets *event*."""
    for name in _names(event):
        package = _PACKAGES.get((name or "").partition(".")[0])
        if package:
            return package
    return _declared


def transport_options():
    """The Sentry client options that decide where events go."""
    dsn = os.environ.get("IMUNITY360_SENTRY_DSN")
    if dsn is not None:
        # a developer's override takes every event; "" sends nothing
        return {"dsn": dsn}
    try:
        with open(DSNS_FILE, encoding="ascii") as file:
            dsns = json.load(file)
        return {"dsn": dsns[CORE], "transport": RoutingTransport(dsns)}
    except Exception:
        # no usable file: send nothing, as without the package
        return {"dsn": ""}


class RoutingTransport(transport.Transport):
    """One HttpTransport per project, each with its own rate limits."""

    def __init__(self, dsns):
        super().__init__({"dsn": dsns[CORE]})
        self._projects = {
            package: transport.HttpTransport(
                dict(DEFAULT_OPTIONS, dsn=dsns[package])
            )
            for package in _PACKAGES.values()
        }

    def capture_event(self, event):
        package = package_of(event)
        event.setdefault("tags", {})["package"] = package
        self._projects[package].capture_event(event)

    def capture_envelope(self, envelope):
        # sessions; the agent sends no transactions or attachments
        self._projects[CORE].capture_envelope(envelope)

    def flush(self, timeout, callback=None):
        deadline = time.monotonic() + timeout
        for project in self._projects.values():
            project.flush(max(deadline - time.monotonic(), 0), callback)

    def kill(self):
        for project in self._projects.values():
            project.kill()
