"""Official Moolre server SDK for Python (standard library only, Python 3.9+).

    import moolre
    client = moolre.Moolre(environment="sandbox", user="acme", api_key="...", pub_key="...",
                           account_number="10000001")
    result = client.payments.initiate(channel="MTN", currency="GHS", payer="0241234567",
                                      amount="1.00", external_ref="PAY-1001",
                                      idempotency_key=moolre.new_idempotency_key())
    print(result.code, result.request_id)

Docs: https://docs.moolre.com/sdks
"""
from __future__ import annotations

import hashlib
import hmac
import json
import random
import re
import socket
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from typing import Any, Dict, Iterator, List, Optional, Sequence

__version__ = "0.1.2"

BASE_URLS = {"live": "https://api.moolre.com", "sandbox": "https://sandbox.moolre.com"}

__all__ = [
    "Moolre", "Result", "MoolreError", "ConfigurationError", "NetworkError", "RequestTimeoutError",
    "InvalidResponseError", "ApiError", "AuthenticationError", "NotFoundError", "ValidationError",
    "IdempotencyError", "RateLimitError", "ServerError", "WebhookSignatureError", "WebhookEvent",
    "verify_webhook", "check_webhook", "parse_webhook", "construct_event", "sign_webhook",
    "new_idempotency_key", "BASE_URLS", "__version__",
]


# --------------------------------------------------------------------------- errors


class MoolreError(Exception):
    """Base class for every error raised by the SDK."""


class ConfigurationError(MoolreError):
    """Misconfiguration, e.g. a credential the call needs is missing."""


class NetworkError(MoolreError):
    """No usable HTTP response (DNS, TLS, reset). """


class RequestTimeoutError(NetworkError):
    """The request exceeded timeout."""


class InvalidResponseError(MoolreError):
    """The HTTP response was not Moolre JSON (e.g. an HTML 502 page)."""

    def __init__(self, message: str, http_status: int, body: str, request_id: Optional[str]):
        super().__init__(message)
        self.http_status = http_status
        self.body = body
        self.request_id = request_id


class ApiError(MoolreError):
    """The API answered status 0 (or a 4xx/5xx in strict mode)."""

    def __init__(self, result: "Result"):
        msg = " ".join(result.message) if isinstance(result.message, list) else str(result.message or "")
        super().__init__("%s: %s" % (result.code, msg))
        self.code = result.code
        self.api_message = msg
        self.fields = _fields_of(result.data)
        self.request_id = result.request_id
        self.http_status = result.http_status
        self.notices = result.notices
        self.result = result


class AuthenticationError(ApiError):
    """AIN01, AIN03, IN01, SW05 or HTTP 401."""


class NotFoundError(ApiError):
    """HTTP 404 in strict mode."""


class ValidationError(ApiError):
    """HTTP 400/422 in strict mode."""


class IdempotencyError(ApiError):
    """IDEM01 / HTTP 409: Idempotency-Key reused with a different request."""


class RateLimitError(ApiError):
    """OTP429 / HTTP 429."""


class ServerError(ApiError):
    """HTTP 5xx with a Moolre JSON body."""


class WebhookSignatureError(MoolreError):
    """reason is one of: malformed, mismatch, timestamp."""

    def __init__(self, reason: str, message: str):
        super().__init__(message)
        self.reason = reason


def _fields_of(data: Any) -> List[str]:
    if isinstance(data, str) and data not in ("", "all"):
        return [data]
    if isinstance(data, list):
        return [x for x in data if isinstance(x, str)]
    return []


_AUTH_CODES = {"AIN01", "AIN03", "IN01", "SW05"}


def _classify(result: "Result") -> ApiError:
    http = result.http_status
    if result.code == "IDEM01" or http == 409:
        return IdempotencyError(result)
    if result.code == "OTP429" or http == 429:
        return RateLimitError(result)
    if http == 401 or result.code in _AUTH_CODES:
        return AuthenticationError(result)
    if http == 404:
        return NotFoundError(result)
    if http in (400, 422):
        return ValidationError(result)
    if http >= 500:
        return ServerError(result)
    return ApiError(result)


# --------------------------------------------------------------------------- result


class Result:
    """What every call returns. `raw` is the untouched response JSON."""

    def __init__(self, raw: Dict[str, Any], http_status: int, header_request_id: Optional[str]):
        status = raw.get("status", 1 if 200 <= http_status < 300 else 0)
        self.raw = raw
        self.http_status = http_status
        self.status = status
        self.ok = str(status) == "1"
        code = raw.get("code")
        self.code = "" if code is None else str(code)
        self.message = raw.get("message")
        self.data = raw.get("data")
        self.go = raw.get("go")
        # Request id: meta.requestid, else legacy top-level request_id, else the X-Request-Id header.
        # Notices: meta.notices, else legacy top-level notices, else [].
        meta = raw.get("meta")
        meta = meta if isinstance(meta, dict) else {}
        rid = meta.get("requestid")
        if not isinstance(rid, str):
            rid = raw.get("request_id")
        self.request_id = rid if isinstance(rid, str) else header_request_id
        notices = meta.get("notices")
        if not isinstance(notices, list):
            notices = raw.get("notices")
        self.notices: List[Dict[str, Any]] = notices if isinstance(notices, list) else []
        self.replayed = meta.get("replayed") is True or raw.get("replayed") is True

    @property
    def otp_required(self) -> bool:
        return self.code == "TP14"

    @property
    def otp_verified(self) -> bool:
        return self.code == "TP17"

    def __repr__(self) -> str:
        return "<moolre.Result ok=%s code=%s request_id=%s>" % (self.ok, self.code, self.request_id)


def new_idempotency_key() -> str:
    """A random Idempotency-Key. Store it with your order and reuse it when retrying."""
    return str(uuid.uuid4())


# --------------------------------------------------------------------------- webhooks

_T_RE = re.compile(r"^[0-9]{1,15}$")
_SIG_RE = re.compile(r"^[0-9a-fA-F]{64}$")


def _to_bytes(body: Any) -> bytes:
    return body.encode("utf-8") if isinstance(body, str) else bytes(body)


def check_webhook(raw_body: Any, signature_header: Optional[str], secret: str,
                  tolerance_sec: int = 300, now: Optional[int] = None) -> Optional[str]:
    """Returns None when valid, otherwise 'malformed' | 'mismatch' | 'timestamp' (Contract W)."""
    if not isinstance(signature_header, str) or signature_header == "" or not secret:
        return "malformed"
    t: Optional[str] = None
    sigs: List[str] = []
    for part in signature_header.split(","):
        if "=" not in part:
            continue
        k, v = part.split("=", 1)
        k, v = k.strip(), v.strip()
        if k == "t" and t is None:
            t = v
        elif k == "v1":
            sigs.append(v)
    if t is None or not _T_RE.match(t):
        return "malformed"
    valid = [s for s in sigs if _SIG_RE.match(s)]
    if not valid:
        return "malformed"
    expected = hmac.new(secret.encode("utf-8"), t.encode("ascii") + b"." + _to_bytes(raw_body), hashlib.sha256).digest()
    match = False
    for s in valid:
        if hmac.compare_digest(expected, bytes.fromhex(s)):
            match = True
    if not match:
        return "mismatch"
    current = int(time.time()) if now is None else now
    if tolerance_sec > 0 and abs(current - int(t)) > tolerance_sec:
        return "timestamp"
    return None


def verify_webhook(raw_body: Any, signature_header: Optional[str], secret: str,
                   tolerance_sec: int = 300, now: Optional[int] = None) -> bool:
    """Verify X-Moolre-Signature (`t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>`).

    Pass the RAW request body (str or bytes), never re-serialised JSON.
    """
    return check_webhook(raw_body, signature_header, secret, tolerance_sec, now) is None


class WebhookEvent:
    def __init__(self, raw: Dict[str, Any]):
        self.raw = raw
        self.event_id: Optional[str] = raw.get("event_id")
        self.event: Optional[str] = raw.get("event")
        self.created: Optional[str] = raw.get("created")
        self.status = raw.get("status")
        self.code = raw.get("code")
        self.message = raw.get("message")
        self.data = raw.get("data")
        meta = raw.get("meta")
        n = meta.get("notices") if isinstance(meta, dict) else None
        if not isinstance(n, list):
            n = raw.get("notices")
        self.notices: List[Dict[str, Any]] = n if isinstance(n, list) else []


def parse_webhook(raw_body: Any) -> WebhookEvent:
    """Parse a webhook body into an event. Does not verify anything."""
    text = raw_body.decode("utf-8") if isinstance(raw_body, (bytes, bytearray)) else raw_body
    raw = json.loads(text)
    if not isinstance(raw, dict):
        raise WebhookSignatureError("malformed", "Webhook body is not a JSON object")
    return WebhookEvent(raw)


def construct_event(raw_body: Any, signature_header: Optional[str], secret: str,
                    tolerance_sec: int = 300, now: Optional[int] = None) -> WebhookEvent:
    """Verify then parse; raises WebhookSignatureError(reason)."""
    failure = check_webhook(raw_body, signature_header, secret, tolerance_sec, now)
    if failure:
        raise WebhookSignatureError(failure, "Invalid Moolre webhook signature (%s)" % failure)
    return parse_webhook(raw_body)


def sign_webhook(raw_body: Any, secret: str, now: Optional[int] = None) -> str:
    """Test helper: build a signature header the way Moolre signs."""
    t = int(time.time()) if now is None else now
    v1 = hmac.new(secret.encode("utf-8"), str(t).encode("ascii") + b"." + _to_bytes(raw_body), hashlib.sha256).hexdigest()
    return "t=%d,v1=%s" % (t, v1)


# --------------------------------------------------------------------------- transport

_KEY_RE = re.compile(r"^[\x20-\x7e]{1,128}$")
_CHANNELS = ("MTN", "TELECEL", "AT", "BANK")
_LEGACY_VALIDATE_ID = {"MTN": "1", "TELECEL": "6", "AT": "7", "BANK": "2"}


def _channel(c: Any) -> str:
    s = str(c).strip()
    return s.upper() if s.upper() in _CHANNELS else s  # legacy numeric ids pass through (deprecated)


def _amount(a: Any) -> str:
    if isinstance(a, (int, float)) and not isinstance(a, bool):
        return "%.2f" % a
    return str(a)


def _clean(d: Dict[str, Any]) -> Dict[str, Any]:
    return {k: v for k, v in d.items() if v is not None}


class _Logger:
    def warn(self, message: str) -> None:  # pragma: no cover - trivial
        sys.stderr.write(message + "\n")


class _Transport:
    def __init__(self, options: Dict[str, Any]):
        env = options.get("environment") or "live"
        if env not in BASE_URLS:
            raise ConfigurationError('environment must be "live" or "sandbox", got %r' % (env,))
        self.user = options.get("user")
        self.api_key = options.get("api_key")
        self.pub_key = options.get("pub_key")
        self.vas_key = options.get("vas_key")
        self.account_number = options.get("account_number")
        self.strict = bool(options.get("strict_http_status"))
        self.throw_on_error = options.get("throw_on_error", True)
        self.max_retries = options.get("max_retries", 2)
        self.retry_delay = options.get("retry_delay", 0.5)
        self.timeout = options.get("timeout", 60.0)
        self.base_url = (options.get("base_url") or BASE_URLS[env]).rstrip("/")
        logger = options.get("logger", "default")
        self.logger = _Logger() if logger == "default" else logger
        self._seen: set = set()

    def call(self, path: str, body: Optional[Dict[str, Any]] = None, *, method: str = "POST",
             query: Optional[Dict[str, Any]] = None, retry: str = "never",
             idempotency_key: Optional[str] = None, needs: Sequence[str] = ()) -> Result:
        if not self.user:
            raise ConfigurationError("`user` (X-API-USER) is required")
        if needs and not any(getattr(self, n) for n in needs):
            names = {"api_key": "api_key (X-API-KEY)", "pub_key": "pub_key (X-API-PUBKEY)", "vas_key": "vas_key (X-API-VASKEY)"}
            raise ConfigurationError("This call needs " + " or ".join(names[n] for n in needs))
        if idempotency_key is not None and not _KEY_RE.match(idempotency_key):
            raise ConfigurationError("idempotency_key must be 1-128 printable ASCII characters")

        url = self.base_url + path
        if query:
            qs = urllib.parse.urlencode({k: str(v) for k, v in _clean(query).items()})
            if qs:
                url += "?" + qs
        headers = {"Accept": "application/json", "User-Agent": "moolre-python/" + __version__, "X-API-USER": self.user}
        if self.api_key:
            headers["X-API-KEY"] = self.api_key
        if self.pub_key:
            headers["X-API-PUBKEY"] = self.pub_key
        if self.vas_key:
            headers["X-API-VASKEY"] = self.vas_key
        if self.strict:
            headers["X-Moolre-Http-Status"] = "strict"
        if idempotency_key is not None:
            headers["Idempotency-Key"] = idempotency_key
        data = None
        if method == "POST":
            headers["Content-Type"] = "application/json"
            data = json.dumps(_clean(body or {}), separators=(",", ":")).encode("utf-8")

        retryable = retry == "read" or (retry == "idempotent" and idempotency_key is not None)
        max_retries = self.max_retries if retryable else 0
        attempt = 0
        while True:
            status, text, req_id, err = self._send(url, method, headers, data)
            if err is not None:
                if attempt < max_retries:
                    self._sleep(attempt)
                    attempt += 1
                    continue
                raise err
            if status >= 500 and attempt < max_retries:
                self._sleep(attempt)
                attempt += 1
                continue
            try:
                parsed = json.loads(text)
            except ValueError:
                parsed = None
            if not isinstance(parsed, dict):
                raise InvalidResponseError("Moolre returned a non-JSON response (HTTP %d)" % status, status, text[:500], req_id)
            result = Result(parsed, status, req_id)
            self._log_notices(result)
            if not result.ok and self.throw_on_error:
                raise _classify(result)
            return result

    def _send(self, url: str, method: str, headers: Dict[str, str], data: Optional[bytes]):
        req = urllib.request.Request(url, data=data, headers=headers, method=method)
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as resp:
                return resp.status, resp.read().decode("utf-8", "replace"), resp.headers.get("X-Request-Id"), None
        except urllib.error.HTTPError as e:
            try:
                text = e.read().decode("utf-8", "replace")
            finally:
                e.close()
            return e.code, text, e.headers.get("X-Request-Id") if e.headers else None, None
        except (socket.timeout, TimeoutError) as e:
            return 0, "", None, RequestTimeoutError("Request to %s timed out after %s s" % (url, self.timeout))
        except urllib.error.URLError as e:
            if isinstance(e.reason, (socket.timeout, TimeoutError)):
                return 0, "", None, RequestTimeoutError("Request to %s timed out after %s s" % (url, self.timeout))
            return 0, "", None, NetworkError("Request to %s failed: %s" % (url, e.reason))
        except (OSError, ValueError) as e:
            # http.client errors (RemoteDisconnected, IncompleteRead ...) are OSError/HTTPException subclasses
            return 0, "", None, NetworkError("Request to %s failed: %s" % (url, e))
        except Exception as e:  # http.client.HTTPException
            return 0, "", None, NetworkError("Request to %s failed: %s" % (url, e))

    def _sleep(self, attempt: int) -> None:
        time.sleep(self.retry_delay * (2 ** attempt) * (0.75 + random.random() * 0.5))

    def _log_notices(self, result: Result) -> None:
        if not self.logger:
            return
        for n in result.notices:
            code = str(n.get("code", "")) if isinstance(n, dict) else ""
            if code in self._seen:
                continue
            self._seen.add(code)
            docs = " (%s)" % n.get("docs") if isinstance(n, dict) and n.get("docs") else ""
            self.logger.warn("[moolre] %s: %s%s" % (code, n.get("message", "") if isinstance(n, dict) else "", docs))

    def account(self, account_number: Optional[str]) -> str:
        a = account_number or self.account_number
        if not a:
            raise ConfigurationError("account_number is required (pass it to the call or to the client)")
        return a


def _lookup(external_ref: Optional[str], transaction_id: Optional[str]) -> Dict[str, Any]:
    if external_ref is not None:
        return {"idtype": 1, "id": external_ref}
    if transaction_id is not None:
        return {"idtype": 2, "id": transaction_id}
    raise ConfigurationError("Pass external_ref or transaction_id")


class _Resource:
    def __init__(self, t: _Transport):
        self._t = t


# --------------------------------------------------------------------------- resources


class Payments(_Resource):
    def initiate(self, *, channel: str, currency: str, payer: str, amount: Any, external_ref: str,
                 reference: Optional[str] = None, otp_code: Optional[str] = None,
                 session_id: Optional[str] = None, skip_otp: Optional[bool] = None,
                 account_number: Optional[str] = None, idempotency_key: Optional[str] = None) -> Result:
        """Request a mobile money payment. result.otp_required (TP14) means: ask the customer for the
        SMS code and call verify_otp(); on TP17 call initiate() again without otp_code."""
        return self._t.call("/open/transact/payment", {
            "type": 1, "channel": _channel(channel), "currency": currency, "payer": payer,
            "amount": _amount(amount), "externalref": external_ref, "reference": reference,
            "otpcode": otp_code, "sessionid": session_id, "accountnumber": self._t.account(account_number),
            "skipotp": skip_otp}, needs=("pub_key",), retry="idempotent", idempotency_key=idempotency_key)

    def verify_otp(self, *, otp_code: str, **kwargs: Any) -> Result:
        return self.initiate(otp_code=otp_code, **kwargs)

    def status(self, *, external_ref: Optional[str] = None, transaction_id: Optional[str] = None,
               account_number: Optional[str] = None) -> Result:
        return self._t.call("/open/transact/status", dict(type=1, accountnumber=self._t.account(account_number),
                            **_lookup(external_ref, transaction_id)), needs=("api_key", "pub_key"), retry="read")

    def create_payment_id(self, *, phone: str, name: str, currency: str, external_ref: str,
                          amount: Any = None, account_number: Optional[str] = None) -> Result:
        return self._t.call("/open/account/create", {
            "type": 2, "phone": phone, "name": name, "currency": currency,
            "amount": None if amount is None else _amount(amount), "externalref": external_ref,
            "accountnumber": self._t.account(account_number)}, needs=("pub_key",))

    def create_bank_account(self, *, currency: str, first_name: str, last_name: str, phone: str, email: str,
                            external_ref: str, amount: Any = None, account_number: Optional[str] = None) -> Result:
        return self._t.call("/open/account/create", {
            "type": 9, "currency": currency, "amount": None if amount is None else float(amount),
            "firstname": first_name, "lastname": last_name, "phone": phone, "email": email,
            "externalref": external_ref, "accountnumber": self._t.account(account_number)}, needs=("pub_key",))

    def list_bank_accounts(self, *, account_number: Optional[str] = None) -> Result:
        return self._t.call("/open/transact/status", {"type": 3, "accountnumber": self._t.account(account_number)},
                            needs=("pub_key",), retry="read")

    def account_transactions(self, external_ref: str, *, account_number: Optional[str] = None) -> Result:
        """Payments received on a Payment ID or bank account, and its status."""
        return self._t.call("/open/transact/status", {"type": 2, "externalref": external_ref,
                            "accountnumber": self._t.account(account_number)}, needs=("pub_key",), retry="read")


class PaymentLinks(_Resource):
    def create(self, *, amount: Any, email: str, external_ref: str, currency: str,
               callback: Optional[str] = None, redirect: Optional[str] = None, reusable: bool = False,
               expiration_time: Optional[int] = None, metadata: Optional[Dict[str, Any]] = None,
               account_number: Optional[str] = None) -> Result:
        return self._t.call("/embed/link", {
            "type": 1, "amount": _amount(amount), "email": email, "externalref": external_ref,
            "callback": callback, "redirect": redirect, "reusable": "1" if reusable else "0",
            "expiration_time": expiration_time, "currency": currency,
            "accountnumber": self._t.account(account_number), "metadata": metadata}, needs=("pub_key",))


class Transfers(_Resource):
    def create(self, *, channel: str, currency: str, amount: Any, receiver: str, external_ref: str,
               sub_list_id: Optional[str] = None, reference: Optional[str] = None,
               sender_name: Optional[str] = None, account_number: Optional[str] = None,
               idempotency_key: Optional[str] = None) -> Result:
        """Pay out to a mobile money wallet or bank account (channel MTN/TELECEL/AT/BANK)."""
        return self._t.call("/open/transact/transfer", {
            "type": 1, "channel": _channel(channel), "currency": currency, "amount": _amount(amount),
            "receiver": receiver, "sublistid": sub_list_id, "externalref": external_ref,
            "reference": reference, "sendername": sender_name,
            "accountnumber": self._t.account(account_number)},
            needs=("api_key",), retry="idempotent", idempotency_key=idempotency_key)

    def status(self, *, external_ref: Optional[str] = None, transaction_id: Optional[str] = None,
               account_number: Optional[str] = None) -> Result:
        return self._t.call("/open/transact/status", dict(type=1, accountnumber=self._t.account(account_number),
                            **_lookup(external_ref, transaction_id)), needs=("api_key", "pub_key"), retry="read")

    def validate_name(self, *, channel: str, currency: str, receiver: str, sub_list_id: Optional[str] = None,
                      account_number: Optional[str] = None) -> Result:
        """Confirm the account holder's name before paying out."""
        name = _channel(channel)
        # /open/transact/validate currently reads the numeric channel ids only.
        return self._t.call("/open/transact/validate", {
            "type": 1, "receiver": receiver, "channel": _LEGACY_VALIDATE_ID.get(name, name),
            "sublistid": sub_list_id, "currency": currency, "accountnumber": self._t.account(account_number)},
            needs=("api_key", "pub_key"), retry="read")

    def internal(self, *, currency: str, amount: Any, receiver: str, external_ref: str,
                 reference: Optional[str] = None, account_number: Optional[str] = None) -> Result:
        """Move money between two Moolre accounts (receiver is an account number)."""
        return self._t.call("/open/transact/internal", {
            "type": 1, "currency": currency, "amount": _amount(amount), "receiver": receiver,
            "externalref": external_ref, "reference": reference,
            "accountnumber": self._t.account(account_number)}, needs=("api_key",))


class Accounts(_Resource):
    def status(self, *, account_number: Optional[str] = None) -> Result:
        return self._t.call("/open/account/status", {"type": 1, "accountnumber": self._t.account(account_number)},
                            needs=("api_key",), retry="read")

    def update(self, *, account_name: Optional[str] = None, currency: str = "GHS", api: Optional[bool] = None,
               callback: Optional[str] = None, settlement: Optional[Dict[str, Any]] = None,
               account_number: Optional[str] = None) -> Result:
        return self._t.call("/open/account/update", {
            "type": 1, "accountnumber": self._t.account(account_number), "accountname": account_name,
            "currency": currency, "api": api, "callback": callback, "settlement": settlement}, needs=("api_key",))

    def create(self, *, account_name: str, callback: str, currency: str = "GHS", api: Optional[bool] = None,
               settlement: Optional[Dict[str, Any]] = None) -> Result:
        """Sandbox only: create a test wallet."""
        return self._t.call("/open/account/create", {
            "type": 1, "accountname": account_name, "currency": currency, "api": api, "callback": callback,
            "settlement": settlement or {"currency": currency, "frequency": "", "channel": "", "recipient": "", "sublist": ""}})

    def transactions(self, *, start_date: Optional[str] = None, end_date: Optional[str] = None,
                     status: Optional[int] = None, limit: Optional[int] = None,
                     descending: Optional[bool] = None, start_id: Optional[Any] = None,
                     end_id: Optional[Any] = None, account_number: Optional[str] = None) -> Result:
        """One page of transactions. Use iterate_transactions() to walk all of them."""
        return self._t.call("/open/account/status", {
            "type": 2, "accountnumber": self._t.account(account_number), "startdate": start_date,
            "enddate": end_date, "limit": limit, "status": status,
            "descending": None if descending is None else (1 if descending else 0),
            "startid": start_id, "endid": end_id}, needs=("api_key",), retry="read")

    def iterate_transactions(self, *, page_size: int = 100, max_items: Optional[int] = None,
                             descending: bool = True, start_id: Optional[Any] = None,
                             end_id: Optional[Any] = None, **filters: Any) -> Iterator[Dict[str, Any]]:
        """Iterate every matching transaction using the id cursor (startid/endid): pages never overlap.
        Newest first unless descending=False. Filters: start_date, end_date, status, account_number."""
        size = min(max(page_size, 2), 1000)
        s_id = None if start_id is None else int(start_id)
        e_id = None if end_id is None else int(end_id)
        seen = 0
        while True:
            r = self.transactions(descending=descending, limit=size, start_id=s_id, end_id=e_id, **filters)
            rows = (r.data or {}).get("transactions", []) if isinstance(r.data, dict) else []
            for row in rows:
                if max_items is not None and seen >= max_items:
                    return
                seen += 1
                yield row
            if len(rows) < size:
                return
            ids = [int(x["transactionid"]) for x in rows if str(x.get("transactionid", "")).isdigit()]
            if not ids:
                return
            if descending:
                e_id = min(ids) - 1
                if e_id <= 1:  # the API needs endid > 1
                    return
            else:
                s_id = max(ids) + 1


class Sales(_Resource):
    def airtime(self, *, channel: str, receiver: str, amount: Any, external_ref: str,
                reference: Optional[str] = None, account_number: Optional[str] = None) -> Result:
        return self._t.call("/open/sales/airtime", {
            "type": 1, "channel": _channel(channel), "receiver": receiver, "amount": _amount(amount),
            "currency": "GHS", "accountnumber": self._t.account(account_number),
            "externalref": external_ref, "reference": reference}, needs=("api_key",))

    def data(self, *, channel: str, receiver: str, bundle: str, external_ref: str,
             reference: Optional[str] = None, account_number: Optional[str] = None) -> Result:
        return self._t.call("/open/sales/data", {
            "type": 1, "channel": _channel(channel), "receiver": receiver, "bundle": bundle, "currency": "GHS",
            "accountnumber": self._t.account(account_number), "externalref": external_ref,
            "reference": reference}, needs=("api_key",))

    def bundles(self, *, network: Optional[str] = None, account_number: Optional[str] = None) -> Result:
        return self._t.call("/open/sales/bundles", {
            "accountnumber": self._t.account(account_number),
            "network": None if network is None else _channel(network)}, needs=("api_key",), retry="read")

    def status(self, *, external_ref: Optional[str] = None, transaction_id: Optional[str] = None,
               reference: Optional[str] = None, account_number: Optional[str] = None) -> Result:
        look = {"idtype": 3, "id": reference} if reference is not None else _lookup(external_ref, transaction_id)
        return self._t.call("/open/sales/status", dict(type=1, accountnumber=self._t.account(account_number), **look),
                            needs=("api_key",), retry="read")


class Sms(_Resource):
    def send(self, *, sender_id: str, messages: List[Dict[str, Any]], network: Optional[str] = None) -> Result:
        """messages: [{"recipient": "...", "message": "...", "ref": "..."}]"""
        return self._t.call("/open/sms/send", {"type": 1, "senderid": sender_id, "network": network,
                            "messages": messages}, needs=("vas_key",))

    def status(self, refs: List[str]) -> Result:
        """0 unknown, 1 sent, 2 delivered, 3 failed."""
        return self._t.call("/open/sms/status", {"type": 5, "ref": refs}, needs=("vas_key",), retry="read")

    def balance(self) -> Result:
        return self._t.call("/open/sms/status", {"type": 2}, needs=("vas_key",), retry="read")

    def sender_id_status(self, sender_id: str) -> Result:
        return self._t.call("/open/sms/status", {"type": 1, "senderid": sender_id}, needs=("vas_key",), retry="read")

    def list_sender_ids(self) -> Result:
        return self._t.call("/open/sms/status", {"type": 7}, needs=("vas_key",), retry="read")

    def create_sender_ids(self, sender_ids: List[Dict[str, Any]]) -> Result:
        return self._t.call("/open/sms/query", {"type": 3, "senderids": sender_ids}, needs=("vas_key",))

    def approve_sender_ids(self, sender_ids: List[Dict[str, Any]]) -> Result:
        """Reseller permission required. approve: 0 pending, 1 approved, 2 rejected."""
        return self._t.call("/open/sms/status", {"type": 6, "senderids": sender_ids}, needs=("vas_key",))


class WhatsApp(_Resource):
    def templates(self, next: Optional[str] = None) -> Result:
        """One page of approved templates; `next` is the cursor from the previous page (result.raw['next'])."""
        return self._t.call("/open/whatsapp/template", method="GET", query={"next": next},
                            needs=("vas_key",), retry="read")

    def iterate_templates(self, max_items: Optional[int] = None) -> Iterator[Dict[str, Any]]:
        nxt: Optional[str] = None
        seen = 0
        while True:
            r = self.templates(nxt)
            for t in r.data or []:
                if max_items is not None and seen >= max_items:
                    return
                seen += 1
                yield t
            n = r.raw.get("next")
            if not (isinstance(n, str) and n):
                return
            nxt = n

    def send(self, *, template_name: str, language: str, messages: List[Dict[str, Any]]) -> Result:
        return self._t.call("/open/whatsapp/send", {"template_name": template_name, "language": language,
                            "messages": messages}, needs=("vas_key",))

    def status(self, refs: List[str]) -> Result:
        return self._t.call("/open/whatsapp/status", {"ref": refs}, needs=("vas_key",), retry="read")


class Reference(_Resource):
    def banks(self, country: str = "gha") -> Result:
        """Supported banks and their codes (use as sub_list_id)."""
        return self._t.call("/open/transact/data", method="GET", query={"country": country, "data": "banks"},
                            needs=("api_key", "pub_key"), retry="read")


def _bulk_item(i: Dict[str, Any]) -> Dict[str, Any]:
    return _clean({
        "externalref": i["external_ref"], "receiver": i["receiver"], "channel": _channel(i["channel"]),
        "amount": _amount(i["amount"]), "sublistid": i.get("sub_list_id"),
        "sendername": i.get("sender_name"), "reference": i.get("reference")})


class Bulk(_Resource):
    def create(self, *, currency: str, batch_ref: str, items: List[Dict[str, Any]],
               callback: Optional[str] = None, atomic: Optional[bool] = None,
               account_number: Optional[str] = None, idempotency_key: Optional[str] = None) -> Result:
        """Submit 1 to 500 payouts. items: [{"external_ref", "receiver", "channel", "amount",
        "sender_name"?, "reference"?, "sub_list_id"?}]. data: batchid, batchref, accepted,
        rejected [{index, code, message, externalref}], total_amount, status "queued", balance_warning?.
        The same batch_ref and body again replays the batch (BLK02, replayed=True)."""
        return self._t.call("/open/transact/bulk", {
            "type": 1, "accountnumber": self._t.account(account_number), "currency": currency,
            "batchref": batch_ref, "callback": callback, "atomic": atomic,
            "items": [_bulk_item(i) for i in items]},
            needs=("api_key",), retry="idempotent", idempotency_key=idempotency_key)

    def status(self, *, batch_id: Optional[str] = None, batch_ref: Optional[str] = None,
               status: Optional[str] = None, after: Optional[int] = None, limit: Optional[int] = None,
               account_number: Optional[str] = None) -> Result:
        """Batch summary plus one page of items. Use iterate_items() to walk them all."""
        return self._t.call("/open/transact/bulk_status", {
            "accountnumber": self._t.account(account_number), "batchid": batch_id, "batchref": batch_ref,
            "status": status, "after": after, "limit": limit}, needs=("api_key",), retry="read")

    def iterate_items(self, *, batch_id: Optional[str] = None, batch_ref: Optional[str] = None,
                      status: Optional[str] = None, page_size: int = 100, max_items: Optional[int] = None,
                      account_number: Optional[str] = None) -> Iterator[Dict[str, Any]]:
        """Walk every item of a batch (follows data.next_after)."""
        size = min(max(page_size, 1), 500)
        after: Optional[int] = None
        seen = 0
        while True:
            r = self.status(batch_id=batch_id, batch_ref=batch_ref, status=status, after=after, limit=size,
                            account_number=account_number)
            d = r.data if isinstance(r.data, dict) else {}
            for item in d.get("items") or []:
                if max_items is not None and seen >= max_items:
                    return
                seen += 1
                yield item
            nxt = d.get("next_after")
            if nxt is None:
                return
            after = int(nxt)

    def list(self, *, limit: Optional[int] = None, starting_after: Optional[str] = None,
             status: Optional[str] = None, account_number: Optional[str] = None) -> Result:
        """Recent batches, newest first. data = {batches, has_more, next_cursor}."""
        return self._t.call("/open/transact/bulk_list", {
            "accountnumber": self._t.account(account_number), "limit": limit,
            "starting_after": starting_after, "status": status}, needs=("api_key",), retry="read")

    def iterate_batches(self, *, status: Optional[str] = None, page_size: int = 25,
                        max_items: Optional[int] = None, account_number: Optional[str] = None) -> Iterator[Dict[str, Any]]:
        after: Optional[str] = None
        seen = 0
        while True:
            r = self.list(limit=min(page_size, 100), starting_after=after, status=status, account_number=account_number)
            d = r.data if isinstance(r.data, dict) else {}
            for b in d.get("batches") or []:
                if max_items is not None and seen >= max_items:
                    return
                seen += 1
                yield b
            if not d.get("has_more") or not d.get("next_cursor"):
                return
            after = str(d["next_cursor"])


class Invoices(_Resource):
    def create(self, *, currency: str, invoice_name: str, customer: Dict[str, Any], due_date: str,
               amount: Any = None, items: Optional[List[Dict[str, Any]]] = None, tax: Optional[float] = None,
               narration: Optional[str] = None, reference: Optional[str] = None,
               metadata: Optional[Dict[str, Any]] = None, service_id: Optional[str] = None,
               account_number: Optional[str] = None, idempotency_key: Optional[str] = None) -> Result:
        """Create an invoice (the same invoices the dashboard shows); give the customer
        result.data['payment_link']. The same reference and body again replays it (INV02).
        items: [{"description", "quantity"?, "amount"}] or pass amount for a single line."""
        lines = None
        if items is not None:
            lines = [_clean({"description": i["description"], "quantity": i.get("quantity"),
                             "amount": _amount(i["amount"])}) for i in items]
        return self._t.call("/open/invoice/create", {
            "accountnumber": self._t.account(account_number), "currency": currency, "service_id": service_id,
            "invoice_name": invoice_name, "customer": customer,
            "amount": None if amount is None else _amount(amount), "items": lines, "tax": tax,
            "due_date": due_date, "narration": narration, "reference": reference, "metadata": metadata},
            needs=("api_key",), retry="idempotent", idempotency_key=idempotency_key)

    def status(self, *, invoice_id: Optional[str] = None, reference: Optional[str] = None,
               account_number: Optional[str] = None) -> Result:
        return self._t.call("/open/invoice/status", {
            "accountnumber": self._t.account(account_number), "invoiceid": invoice_id, "reference": reference},
            needs=("api_key",), retry="read")

    def list(self, *, limit: Optional[int] = None, starting_after: Optional[str] = None,
             status: Optional[str] = None, reference: Optional[str] = None, service_id: Optional[str] = None,
             account_number: Optional[str] = None) -> Result:
        """data = {invoices, has_more, next_cursor}, newest first."""
        return self._t.call("/open/invoice/list", {
            "accountnumber": self._t.account(account_number), "limit": limit, "starting_after": starting_after,
            "status": status, "reference": reference, "service_id": service_id},
            needs=("api_key",), retry="read")

    def iterate(self, *, page_size: int = 25, max_items: Optional[int] = None, **filters: Any) -> Iterator[Dict[str, Any]]:
        after: Optional[str] = None
        seen = 0
        while True:
            r = self.list(limit=min(page_size, 100), starting_after=after, **filters)
            d = r.data if isinstance(r.data, dict) else {}
            for inv in d.get("invoices") or []:
                if max_items is not None and seen >= max_items:
                    return
                seen += 1
                yield inv
            if not d.get("has_more") or not d.get("next_cursor"):
                return
            after = str(d["next_cursor"])

    def cancel(self, invoice_id: str, *, account_number: Optional[str] = None) -> Result:
        """Cancel an unpaid invoice (its hosted link stops working). INV18 if it has payments."""
        return self._t.call("/open/invoice/cancel", {"accountnumber": self._t.account(account_number),
                            "invoiceid": invoice_id}, needs=("api_key",))


class Webhooks(_Resource):
    def deliveries(self, *, event: Optional[str] = None, state: Optional[str] = None,
                   from_: Optional[str] = None, to: Optional[str] = None, limit: Optional[int] = None,
                   starting_after: Optional[str] = None, include_payload: bool = False,
                   account_number: Optional[str] = None) -> Result:
        """Webhooks Moolre has sent (or is retrying), newest first. data = {items, has_more, next_cursor}."""
        return self._t.call("/open/webhook/deliveries", {
            "accountnumber": self._t.account(account_number), "event": event, "state": state, "from": from_,
            "to": to, "limit": limit, "starting_after": starting_after,
            "include_payload": 1 if include_payload else None}, needs=("api_key",), retry="read")

    def iterate_deliveries(self, *, page_size: int = 25, max_items: Optional[int] = None,
                           starting_after: Optional[str] = None, **filters: Any) -> Iterator[Dict[str, Any]]:
        after = starting_after
        seen = 0
        while True:
            r = self.deliveries(limit=min(page_size, 100), starting_after=after, **filters)
            d = r.data if isinstance(r.data, dict) else {}
            for row in d.get("items") or []:
                if max_items is not None and seen >= max_items:
                    return
                seen += 1
                yield row
            if not d.get("has_more") or not d.get("next_cursor"):
                return
            after = str(d["next_cursor"])

    def resend(self, event_id: str, *, account_number: Optional[str] = None) -> Result:
        """Put an event back in the delivery queue (same event_id, full retry schedule)."""
        return self._t.call("/open/webhook/resend", {"accountnumber": self._t.account(account_number),
                            "event_id": event_id}, needs=("api_key",))

    def test(self, *, account_number: Optional[str] = None) -> Result:
        """Send a signed `webhook.test` event to the wallet's callback URL now.
        data = {event_id, delivered, http, error}."""
        return self._t.call("/open/webhook/test", {"accountnumber": self._t.account(account_number)},
                            needs=("api_key",))

    verify = staticmethod(verify_webhook)
    construct_event = staticmethod(construct_event)
    parse = staticmethod(parse_webhook)


class Moolre:
    """Client. Options: environment ('live'|'sandbox'), base_url, user, api_key, pub_key, vas_key,
    account_number, strict_http_status, throw_on_error, max_retries, retry_delay, timeout, logger."""

    def __init__(self, *, environment: str = "live", user: Optional[str] = None, api_key: Optional[str] = None,
                 pub_key: Optional[str] = None, vas_key: Optional[str] = None,
                 account_number: Optional[str] = None, base_url: Optional[str] = None,
                 strict_http_status: bool = False, throw_on_error: bool = True, max_retries: int = 2,
                 retry_delay: float = 0.5, timeout: float = 60.0, logger: Any = "default"):
        t = _Transport(dict(environment=environment, user=user, api_key=api_key, pub_key=pub_key,
                            vas_key=vas_key, account_number=account_number, base_url=base_url,
                            strict_http_status=strict_http_status, throw_on_error=throw_on_error,
                            max_retries=max_retries, retry_delay=retry_delay, timeout=timeout, logger=logger))
        self._transport = t
        self.payments = Payments(t)
        self.payment_links = PaymentLinks(t)
        self.transfers = Transfers(t)
        self.accounts = Accounts(t)
        self.sales = Sales(t)
        self.sms = Sms(t)
        self.whatsapp = WhatsApp(t)
        self.reference = Reference(t)
        self.bulk = Bulk(t)
        self.invoices = Invoices(t)
        self.webhooks = Webhooks(t)

    @classmethod
    def from_env(cls, **overrides: Any) -> "Moolre":
        """MOOLRE_ENV, MOOLRE_USER, MOOLRE_API_KEY, MOOLRE_PUBKEY, MOOLRE_VASKEY, MOOLRE_ACCOUNT."""
        import os
        opts: Dict[str, Any] = dict(
            environment="sandbox" if os.environ.get("MOOLRE_ENV") == "sandbox" else "live",
            user=os.environ.get("MOOLRE_USER"), api_key=os.environ.get("MOOLRE_API_KEY"),
            pub_key=os.environ.get("MOOLRE_PUBKEY"), vas_key=os.environ.get("MOOLRE_VASKEY"),
            account_number=os.environ.get("MOOLRE_ACCOUNT"))
        opts.update(overrides)
        return cls(**opts)

    verify_webhook = staticmethod(verify_webhook)
    construct_event = staticmethod(construct_event)
    parse_webhook = staticmethod(parse_webhook)
    new_idempotency_key = staticmethod(new_idempotency_key)
