"""AssertInbox pytest plugin. MIT License. Copyright (c) AssertInbox.

Put this file next to assertinbox.py and add to conftest.py:

    pytest_plugins = ["pytest_assertinbox"]

Set ASSERTINBOX_KEY (and optionally ASSERTINBOX_NAMESPACE; it is read from /v1/me when unset).
"""
import os
import random
import re
import string

from assertinbox import AssertInbox

try:
    import pytest
except ImportError:  # the module stays importable for unit tests without pytest
    pytest = None


def _clean(value, limit):
    return re.sub(r"[^a-z0-9]+", "-", str(value).lower()).strip("-")[:limit].strip("-")


class Inbox:
    """Addresses and waits for one test. Tags are unique per test, xdist worker and instance."""

    def __init__(self, client, nodeid, worker=None):
        self.client = client
        suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=4))
        self._base = "py-%s-%s-%s" % (_clean(nodeid, 24) or "test", _clean(worker or "main", 8) or "main", suffix)
        self._used = []
        self._current = self._tag_for("user")
        self.defaults = {"timeout": 25, "retries": 2}

    def _tag_for(self, name):
        return ("%s-%s" % (self._base, _clean(name, 16) or "user"))[:64].strip("-")

    @property
    def tag(self):
        return self._current

    def address(self, name="user"):
        self._current = self._tag_for(name)
        if self._current not in self._used:
            self._used.append(self._current)
        return self.client.address(self._current)

    def _options(self, options):
        merged = dict(self.defaults)
        merged.update(options)
        return merged

    def wait(self, **filters):
        tag = filters.pop("tag", None) or self._current
        return self.client.wait(tag, **self._options(filters))

    def wait_for_otp(self, **filters):
        return self.client.wait_for_otp(self._current, **self._options(filters))

    def wait_for_link(self, **filters):
        return self.client.wait_for_link(self._current, **self._options(filters))

    def cleanup(self):
        for tag in self._used:
            try:
                self.client.delete(tag)
            except Exception:  # cleanup problems must not fail the test
                pass


def make_inbox(client, nodeid, worker=None):
    return Inbox(client, nodeid, worker)


def _client_from_env():
    key = os.environ.get("ASSERTINBOX_KEY")
    if not key:
        raise RuntimeError("Set ASSERTINBOX_KEY (and optionally ASSERTINBOX_NAMESPACE). Create a key at https://assertinbox.com/start")
    client = AssertInbox(
        key,
        os.environ.get("ASSERTINBOX_NAMESPACE"),
        base_url=os.environ.get("ASSERTINBOX_URL") or "https://assertinbox.com",
        domain=os.environ.get("ASSERTINBOX_DOMAIN") or None,
    )
    if not client.namespace:
        client.namespace = client.me()["namespace"]
    return client


if pytest is not None:

    @pytest.fixture
    def inbox(request):
        inbox = make_inbox(_client_from_env(), request.node.nodeid, os.environ.get("PYTEST_XDIST_WORKER"))
        yield inbox
        inbox.cleanup()
