# Ninja SMS API client for Python 3.8+. One file, standard library only.
# Docs: https://ninjasms.shop/docs
#
#   from ninjasms import Client
#   api = Client(os.environ["NSK_KEY"])
#   number = api.buy("wa", 2, 0.13, idempotency_key="order-1042")  # your own id for this order
#   # A timeout or network error? Call buy() again with the SAME key: it can never buy twice.
#   print(api.wait_for_code(number["id"]))
#
# Keep your API key on a server. Never ship it in an app.

import json
import re
import time
import urllib.error
import urllib.request


_KEY = re.compile(r"^[A-Za-z0-9_.:-]{1,128}$")


def _require_key(idempotency_key):
    if not isinstance(idempotency_key, str) or not _KEY.match(idempotency_key):
        raise ValueError("Pass idempotency_key: your own id for this order (1-128 of A-Z a-z 0-9 _ . : -). "
                         "Reuse it to retry the same order; a new one buys again.")


class ApiError(Exception):
    def __init__(self, message, status, code=None, body=None):
        super().__init__(message)
        self.status = status
        self.code = code
        self.body = body


class Client:
    def __init__(self, api_key, base_url="https://ninjasms.shop", timeout=60):
        if not api_key:
            raise ValueError("An API key is required (Settings -> API).")
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout

    def call(self, operation, input=None, idempotency_key=None):
        """Any operation. A purchase-like call needs an Idempotency-Key: keep the same key for every
        retry of one order and a retry can never buy twice. Drop it only after a success or
        already_completed."""
        payload = {"operation": operation}
        if input is not None:
            payload["input"] = input
        headers = {"Authorization": "Bearer " + self.api_key, "Content-Type": "application/json"}
        if idempotency_key:
            headers["Idempotency-Key"] = idempotency_key
        req = urllib.request.Request(self.base_url + "/api/sms", data=json.dumps(payload).encode(), headers=headers, method="POST")
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as res:
                body = json.loads(res.read().decode() or "{}")
                status = res.status
        except urllib.error.HTTPError as e:
            try:
                body = json.loads(e.read().decode() or "{}")
            except ValueError:
                body = {}
            raise ApiError(body.get("error") or "HTTP %d" % e.code, e.code, body.get("code"), body)
        if body.get("ok") is False:
            raise ApiError(body.get("error") or "HTTP %d" % status, status, body.get("code"), body)
        return body.get("data", body)

    def balance(self):
        """Your balance."""
        return self.call("balance.read", None)

    def services(self):
        """The services on sale, with their codes."""
        return self.call("catalog.services", None)

    def countries(self):
        """The countries, with their ids."""
        return self.call("catalog.countries", None)

    def prices(self, service, **options):
        """Your price and stock. type is sms (default), call or rent; a rental also needs duration in hours."""
        return self.call("catalog.prices", {"service": service, **options})

    def buy(self, service, country, expected_price, idempotency_key=None, **options):
        """Buy one number. Needs an Idempotency-Key header. For several numbers, send several purchases, each with its own key. idempotency_key: your own id for this order; send the same one to retry it."""
        _require_key(idempotency_key)
        return self.call("activation.purchase", {"service": service, "country": country, "expectedPrice": expected_price, **options}, idempotency_key)

    def status(self, id):
        """One number and its code, once it has arrived."""
        return self.call("activation.status", {"id": id})

    def messages(self, id):
        """Every SMS a number received, newest first (a rental keeps receiving until it ends)."""
        return self.call("activation.messages", {"id": id})

    def transition(self, id, transition):
        """Cancel for a refund, or complete once you have the code."""
        return self.call("activation.transition", {"id": id, "transition": transition})

    def reactivation_quote(self, id):
        """Price of a second code on a number that already received one."""
        return self.call("activation.reactivation.quote", {"id": id})

    def reactivate(self, id, expected_price, idempotency_key=None):
        """Buy that second code. Same Idempotency-Key and price rules as a purchase. idempotency_key: your own id for this order; send the same one to retry it."""
        _require_key(idempotency_key)
        return self.call("activation.reactivation.purchase", {"id": id, "expectedPrice": expected_price}, idempotency_key)

    def replace_quote(self, id):
        """Price of a fresh number in place of one still waiting for its code: { price, refund, extra }."""
        return self.call("activation.replace.quote", {"id": id})

    def replace(self, id, expected_price, idempotency_key=None):
        """Swap a waiting number for a fresh one (from 2 minutes after buying). The old one is refunded and the new one charged together. Same Idempotency-Key and price rules as a purchase. idempotency_key: your own id for this order; send the same one to retry it."""
        _require_key(idempotency_key)
        return self.call("activation.replace", {"id": id, "expectedPrice": expected_price}, idempotency_key)

    def active(self):
        """Your numbers that are still waiting or active."""
        return self.call("activations.list", None)

    def history(self, **options):
        """Your past numbers, newest first. q searches phone, service, country, code and label."""
        return self.call("history.list", {**options})

    def wait_for_code(self, id, interval=5, timeout=20 * 60):
        """Polls status() until the code arrives, the number is cancelled, or timeout passes."""
        end = time.time() + timeout
        while True:
            s = self.status(id)
            if s.get("state") in ("received", "cancelled") or time.time() + interval > end:
                return s
            time.sleep(interval)
