"""PayerNex API client for Python 3.8+ (standard library only).

Docs: https://payernex.com/developers/api

    from payernex import PayerNex
    pnx = PayerNex(os.environ["PAYERNEX_API_KEY"])
    order = pnx.create_order(amount=25, currency="USD", ipn_url="https://shop.example/ipn")
    # redirect the buyer to order["checkout_url"]

    # In your IPN handler (use the raw request body bytes):
    event = PayerNex.parse_webhook(raw_body, request.headers.get("X-Signature"), os.environ["PAYERNEX_WEBHOOK_SECRET"])
    fresh = pnx.get_order(event["order_ref"])  # trust this, not the webhook body
    if fresh["status"] == "paid":
        ...
"""

import hashlib
import hmac
import json
import urllib.error
import urllib.parse
import urllib.request

__all__ = ["PayerNex", "PayerNexError"]


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


class PayerNex:
    def __init__(self, api_key, base_url="https://payernex.com", timeout=30):
        if not api_key:
            raise ValueError("PayerNex: an API key is required")
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout

    @property
    def test_mode(self):
        """True when the key is a sandbox key (orders can only be paid by simulation)."""
        return self.api_key.startswith("test_")

    def request(self, method, path, body=None):
        data = json.dumps(body).encode() if body is not None else None
        req = urllib.request.Request(self.base_url + path, data=data, method=method)
        req.add_header("Authorization", "Bearer " + self.api_key)
        req.add_header("Accept", "application/json")
        if data is not None:
            req.add_header("Content-Type", "application/json")
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as res:
                status, text = res.status, res.read().decode("utf-8", "replace")
        except urllib.error.HTTPError as e:
            status, text = e.code, e.read().decode("utf-8", "replace")
        except (urllib.error.URLError, OSError) as e:
            raise PayerNexError("PayerNex request failed: %s" % e)
        try:
            payload = json.loads(text)
        except ValueError:
            payload = None
        if not (200 <= status < 300) or not isinstance(payload, dict) or payload.get("success") is False:
            msg = payload.get("error") if isinstance(payload, dict) and payload.get("error") else "PayerNex HTTP %d" % status
            raise PayerNexError(msg, status, payload if payload is not None else text)
        return payload.get("data", payload)

    def create_order(self, **params):
        """POST /api/v1/create-order. Returns order_ref, checkout_url, amount, currency, expires_at, ..."""
        return self.request("POST", "/api/v1/create-order", params)

    def get_order(self, order_ref):
        return self.request("GET", "/api/v1/order/" + urllib.parse.quote(order_ref, safe=""))

    def cancel_order(self, order_ref):
        """Only pending orders can be cancelled."""
        return self.request("POST", "/api/v1/cancel-order/" + urllib.parse.quote(order_ref, safe=""))

    def create_refund(self, order_ref, amount=None, reason=None, idempotency_key=None):
        """Refund a paid Stripe order, fully or partly."""
        body = {"order_ref": order_ref}
        for k, v in (("amount", amount), ("reason", reason), ("idempotency_key", idempotency_key)):
            if v is not None:
                body[k] = v
        return self.request("POST", "/api/v1/refunds", body)

    def list_refunds(self, order_ref):
        return self.request("GET", "/api/v1/refunds?order_ref=" + urllib.parse.quote(order_ref, safe=""))

    @staticmethod
    def verify_signature(raw_body, signature, secret):
        """Checks X-Signature (order IPN) or X-PayerNex-Signature (webhook endpoint):
        HMAC-SHA256 of the raw body with the matching secret, lowercase hex."""
        if not raw_body or not signature or not secret:
            return False
        if isinstance(raw_body, str):
            raw_body = raw_body.encode("utf-8")
        expected = hmac.new(secret.encode("utf-8"), raw_body, hashlib.sha256).hexdigest()
        return hmac.compare_digest(expected, str(signature).strip().lower())

    @staticmethod
    def parse_webhook(raw_body, signature, secret):
        """Verifies and decodes a webhook body; raises PayerNexError(401) on a bad signature."""
        if not PayerNex.verify_signature(raw_body, signature, secret):
            raise PayerNexError("Invalid PayerNex signature", 401)
        return json.loads(raw_body if isinstance(raw_body, str) else raw_body.decode("utf-8"))
