"""
PalestineX Developer API - Python client

Generated from the API reference on the site, so every method here matches
an endpoint documented there exactly. Standard library only - no pip install.

    from palestinex import PalestineX

    api = PalestineX(api_key="your-key-here")
    print(api.balance())

Or keep the key out of your source:

    export PALESTINEX_API_KEY=your-key-here
    api = PalestineX()                       # reads the variable

Get a key from Profile -> Developer REST API. Rotating a key revokes the old
one immediately, so a rotated key breaks anything still using it.

Errors: AuthenticationError (401/403, or a missing key), RateLimited (429, with
.retry_after), and ApiError for everything else. Each carries .code, .status
and .details taken from the API's own error envelope.
"""

import json as _json
import os as _os
import urllib.error as _urlerror
import urllib.parse as _urlparse
import urllib.request as _urlrequest

__all__ = ["PalestineX", "ApiError", "AuthenticationError", "RateLimited"]


class ApiError(Exception):
    """An error the API returned, with its code and HTTP status."""

    def __init__(self, message, code=None, status=None, details=None):
        super().__init__(message)
        self.message = message
        self.code = code
        self.status = status
        self.details = details


class AuthenticationError(ApiError):
    """The key is missing, wrong, or revoked by a rotation."""


class RateLimited(ApiError):
    """Too many requests. .retry_after is the number of seconds to wait."""

    def __init__(self, message, retry_after=None, **kw):
        super().__init__(message, **kw)
        self.retry_after = retry_after


class PalestineX:
    """Client for the PalestineX Developer API v1."""

    BASE_URL = "https://palestinex.store"

    # No API_PREFIX: the paths below are the documented paths and already
    # begin with /api/v1, so prefixing them again produced a request to
    # /api/v1/api/v1/balance and a 404 from a working integration.

    def __init__(self, api_key=None, base_url=None, timeout=30):
        self.api_key = api_key if api_key is not None else _os.environ.get(
            "PALESTINEX_API_KEY", "")
        self.base_url = (base_url or self.BASE_URL).rstrip("/")
        self.timeout = timeout

    # -------------------------------------------------------------- core

    def request(self, method, path, body=None, query=None, headers=None,
                 idempotency_key=None, auth=True):
        """Send one request and return the decoded body, or raise."""
        if auth and not self.api_key:
            raise AuthenticationError(
                "No API key. Pass api_key=... or set PALESTINEX_API_KEY.",
                code="MISSING_API_KEY", status=401)

        url = self.base_url + path
        if query:
            url += "?" + _urlparse.urlencode(
                {k: v for k, v in query.items() if v is not None})

        payload = None
        send_headers = {
            "Accept": "application/json",
            "User-Agent": "palestinex-python/1.0",
        }
        if self.api_key:
            send_headers["Authorization"] = "Bearer " + self.api_key
        if body is not None:
            payload = _json.dumps(body).encode("utf-8")
            send_headers["Content-Type"] = "application/json"
        if idempotency_key:
            send_headers["Idempotency-Key"] = idempotency_key
        if headers:
            send_headers.update(headers)

        req = _urlrequest.Request(url, data=payload, headers=send_headers,
                                       method=method.upper())

        try:
            with _urlrequest.urlopen(req, timeout=self.timeout) as resp:
                raw = resp.read().decode("utf-8", "replace")
        except _urlerror.HTTPError as exc:
            raw = exc.read().decode("utf-8", "replace")
            raise self._error(raw, exc.code, exc.headers)
        except _urlerror.URLError as exc:
            raise ApiError("Could not reach the API: %s" % (exc.reason,))

        try:
            return _json.loads(raw) if raw else {}
        except ValueError:
            raise ApiError("The API returned something that is not JSON: " + raw[:400])

    def fetch_raw(self, method, path, headers=None):
        """Send one request and return the raw bytes rather than JSON."""
        if not self.api_key:
            raise AuthenticationError(
                "No API key. Pass api_key=... or set PALESTINEX_API_KEY.",
                code="MISSING_API_KEY", status=401)

        url = self.base_url + path
        send = {"Authorization": "Bearer " + self.api_key,
                 "Accept": "application/octet-stream",
                 "User-Agent": "palestinex-python/1.0"}
        if headers:
            send.update(headers)
        req = _urlrequest.Request(url, headers=send, method=method.upper())
        try:
            with _urlrequest.urlopen(req, timeout=self.timeout) as resp:
                return resp.read()
        except _urlerror.HTTPError as exc:
            raise self._error(exc.read().decode("utf-8", "replace"),
                                 exc.code, exc.headers)
        except _urlerror.URLError as exc:
            raise ApiError("Could not reach the API: %s" % (exc.reason,))

    @staticmethod
    def _error(raw, status, headers):
        code, message, details = None, raw, None
        try:
            parsed = _json.loads(raw)
            err = parsed.get("error") or {}
            code = err.get("code")
            message = err.get("message") or parsed.get("message") or raw
            details = err.get("details")
        except Exception:
            pass

        cls = AuthenticationError if status in (401, 403) else (
            RateLimited if status == 429 else ApiError)

        if status == 429:
            retry = headers.get("Retry-After") if headers else None
            try:
                retry = int(retry) if retry else None
            except (TypeError, ValueError):
                retry = None
            return cls(message, retry_after=retry, code=code, status=status,
                         details=details)

        return cls(message, code=code, status=status, details=details)

    def products(self, category=None):
        """
        List the products you can buy

        GET /api/v1/products

        :param category: Return one category only. One of gmail, hotmail, outlook, edu, proxy, custom - or all, which is the default.
        """
        data = {}
        if category is not None:
            data["category"] = category
        return self.request(
            "GET",
            "/api/v1/products",
            body=data or None,
            auth=False,
        )

    def status(self):
        """
        Is the service up?

        GET /api/v1/status

        """
        data = {}
        return self.request(
            "GET",
            "/api/v1/status",
            body=data or None,
            auth=False,
        )

    def balance(self):
        """
        Check your balance

        GET /api/v1/balance

        """
        data = {}
        return self.request(
            "GET",
            "/api/v1/balance",
            body=data or None,
            auth=True,
        )

    def key_rotate(self, idempotency_key=None):
        """
        Rotate your API key

        POST /api/v1/user/api-key/rotate

        :param idempotency_key: Send one on every write. A retry with
            the same value returns the original order instead of buying twice.
        """
        data = {}
        return self.request(
            "POST",
            "/api/v1/user/api-key/rotate",
            idempotency_key=idempotency_key,
            body=data or None,
            auth=True,
        )

    def order_buy(self, productKey, quantity, idempotency_key=None, format=None):
        """
        Buy mail

        POST /api/v1/order/buy

        :param productKey: The `key` of a product from /api/v1/products. The product id is not accepted here - the key is the stable identifier. (required)
        :param quantity: How many accounts to buy. Must be at least 1 and within that product's own `min_quantity` and `max_quantity`. There is no separate global cap. (required)
        :param format: How the accounts come back: txt, csv or xlsx. Defaults to txt. An unrecognised value falls back to txt rather than failing the order.
        :param idempotency_key: Send one on every write. A retry with
            the same value returns the original order instead of buying twice.
        """
        data = {}
        if productKey is None:
            raise ValueError("productKey is required")
        data["productKey"] = productKey
        if quantity is None:
            raise ValueError("quantity is required")
        data["quantity"] = quantity
        if format is not None:
            data["format"] = format
        return self.request(
            "POST",
            "/api/v1/order/buy",
            idempotency_key=idempotency_key,
            body=data or None,
            auth=True,
        )

    def order_bulk(self, orders, idempotency_key=None):
        """
        Buy mail in bulk

        POST /api/v1/order/bulk

        :param orders: Array of 1 to 25 objects, each {product_key, quantity, format?}. (required)
        :param idempotency_key: Send one on every write. A retry with
            the same value returns the original order instead of buying twice.
        """
        data = {}
        if orders is None:
            raise ValueError("orders is required")
        data["orders"] = orders
        return self.request(
            "POST",
            "/api/v1/order/bulk",
            idempotency_key=idempotency_key,
            body=data or None,
            auth=True,
        )

    def order_history(self, page=None, limit=None):
        """
        List your orders

        GET /api/v1/order/history

        :param page: 1-based page number.
        :param limit: Rows per page, 1 to 100. Defaults to 20.
        """
        data = {}
        if page is not None:
            data["page"] = page
        if limit is not None:
            data["limit"] = limit
        return self.request(
            "GET",
            "/api/v1/order/history",
            body=data or None,
            auth=True,
        )

    def order_download(self, code, path_code, format=None, as_=None):
        """
        Download a delivered order

        GET /api/v1/order/{code}/download

        :param code: An order code from the history endpoint. (required)
        :param format: txt, csv or xlsx. Defaults to the format the order was bought in. There is no "json" format - ask for JSON with as=json instead, which returns the envelope with a machine-readable list of the accounts.
        :param as_: Send as=json to get JSON back instead of a file.
        :param path_code: the value that goes in the path. (required)
        """
        data = {}
        if code is None:
            raise ValueError("code is required")
        data["code"] = code
        if format is not None:
            data["format"] = format
        if as_ is not None:
            data["as_"] = as_
        return self.request(
            "GET",
            "/api/v1/order/%s/download" % (_urlparse.quote(str(path_code))),
            body=data or None,
            auth=True,
        )

    def code_fetch(
            self,
            email,
            idempotency_key=None,
            type=None,
            refreshToken=None,
            clientId=None,
            inboxUrl=None
    ):
        """
        Fetch the latest code for a mailbox

        POST /api/v1/code/fetch

        :param email: A mailbox address this account purchased. Any other address resolves to nothing and returns 422. (required)
        :param type: Which service you want the code for - facebook, instagram, telegram and so on. Defaults to all, which returns the newest code whatever it is for.
        :param refreshToken: OAuth2 refresh token. Resolved from your purchase when omitted, so you never have to re-send a secret you already paid for.
        :param clientId: OAuth2 client id. Resolved from your purchase when omitted.
        :param inboxUrl: Live inbox URL, for Gmail pools. Resolved from your purchase when omitted.
        :param idempotency_key: Send one on every write. A retry with
            the same value returns the original order instead of buying twice.
        """
        data = {}
        if email is None:
            raise ValueError("email is required")
        data["email"] = email
        if type is not None:
            data["type"] = type
        if refreshToken is not None:
            data["refreshToken"] = refreshToken
        if clientId is not None:
            data["clientId"] = clientId
        if inboxUrl is not None:
            data["inboxUrl"] = inboxUrl
        return self.request(
            "POST",
            "/api/v1/code/fetch",
            idempotency_key=idempotency_key,
            body=data or None,
            auth=True,
        )

    def proxy_plans(self):
        """
        Proxy prices and limits

        GET /api/v1/proxy/plans

        """
        data = {}
        return self.request(
            "GET",
            "/api/v1/proxy/plans",
            body=data or None,
            auth=False,
        )

    def proxy_create(self, username, gb, idempotency_key=None, unit=None):
        """
        Buy a residential proxy

        POST /api/v1/proxy

        :param username: A name for the proxy at the supplier: 4 to 12 characters, starting with a letter, then letters, digits or underscores. Dots and dashes are rejected by the supplier, so they are refused here too. (required)
        :param gb: How much data to buy, in gigabytes. Between 0.1 and 100. (required)
        :param unit: gb (default) or mb, if you would rather send megabytes.
        :param idempotency_key: Send one on every write. A retry with
            the same value returns the original order instead of buying twice.
        """
        data = {}
        if username is None:
            raise ValueError("username is required")
        data["username"] = username
        if gb is None:
            raise ValueError("gb is required")
        data["gb"] = gb
        if unit is not None:
            data["unit"] = unit
        return self.request(
            "POST",
            "/api/v1/proxy",
            idempotency_key=idempotency_key,
            body=data or None,
            auth=True,
        )

    def proxy_show(self, username, path_username):
        """
        Check a proxy you bought

        GET /api/v1/proxy/{username}

        :param username: The username you passed to create, not the proxy_username the response returned. (required)
        :param path_username: the value that goes in the path. (required)
        """
        data = {}
        if username is None:
            raise ValueError("username is required")
        data["username"] = username
        return self.request(
            "GET",
            "/api/v1/proxy/%s" % (_urlparse.quote(str(path_username))),
            body=data or None,
            auth=True,
        )

if __name__ == "__main__":
    # A quick check that the key works. Run: python palestinex.py
    try:
        account = PalestineX().balance()
        data = account.get("data", account)
        print("Key works. Balance: %s %s" % (data.get("balance"),
                                        data.get("currency")))
    except AuthenticationError as exc:
        print("Authentication failed:", exc.message)
    except ApiError as exc:
        print("API error %s: %s" % (exc.code, exc.message))
