"""NEXUSLAB Payment Gateway — Python SDK (API v1).

Single-file SDK. Requires: requests (pip install requests).

Usage:
    from nexuslab import NexusLab

    nx = NexusLab(api_key="nx_live_or_brand_key", base_url="https://payment.nexuslab.dev.cv")

    pay = nx.create_payment(
        amount=1250.00,
        success_url="https://yourshop.com/payment/success",
        cancel_url="https://yourshop.com/payment/cancel",
        cus_name="Karim Uddin",
        cus_email="karim@example.com",
        webhook_url="https://yourshop.com/webhooks/nexuslab",
        metadata={"order_id": "1001"},
    )
    # pay["payment_url"] -> redirect the customer there
    # pay["transaction_id"] -> store it with the order

    status = nx.verify_payment(pay["transaction_id"])
    if status["status"] == "COMPLETED" and float(status["amount"]) == 1250.00:
        ...  # fulfil the order

Webhook signature check (e.g. in a Flask view):
    ok = NexusLab.verify_webhook_signature(
        raw_body=request.get_data(),
        signature_header=request.headers.get("X-Nexuslab-Signature", ""),
        secret="whsec_...",
    )
"""

import hashlib
import hmac
import json
import time

import requests


class NexusLabError(Exception):
    """Raised when the API returns a standardized v1 error."""

    def __init__(self, code, message, request_id=None, http_status=None):
        super().__init__(f"{code}: {message}")
        self.code = code
        self.message = message
        self.request_id = request_id
        self.http_status = http_status


class NexusLab:
    def __init__(self, api_key, base_url="https://payment.nexuslab.dev.cv", timeout=30):
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout

    # -- internals ---------------------------------------------------------
    def _post(self, path, payload, extra_headers=None):
        headers = {"API-KEY": self.api_key, "Content-Type": "application/json"}
        if extra_headers:
            headers.update(extra_headers)
        resp = requests.post(
            self.base_url + path, headers=headers, json=payload, timeout=self.timeout
        )
        try:
            body = resp.json()
        except ValueError:
            raise NexusLabError(
                "INTERNAL_SERVER_ERROR",
                f"Non-JSON response (HTTP {resp.status_code})",
                http_status=resp.status_code,
            )
        if not body.get("status"):
            err = body.get("error") or {}
            raise NexusLabError(
                err.get("code", "INTERNAL_SERVER_ERROR"),
                err.get("message", "Unknown error"),
                request_id=body.get("request_id"),
                http_status=resp.status_code,
            )
        return body["data"]

    # -- public API --------------------------------------------------------
    def create_payment(
        self,
        amount,
        success_url,
        cancel_url,
        cus_name=None,
        cus_email=None,
        webhook_url=None,
        metadata=None,
        idempotency_key=None,
    ):
        """Create a payment. Returns {"payment_url", "transaction_id", "test"}."""
        payload = {
            "amount": amount,
            "success_url": success_url,
            "cancel_url": cancel_url,
        }
        if cus_name is not None:
            payload["cus_name"] = cus_name
        if cus_email is not None:
            payload["cus_email"] = cus_email
        if webhook_url is not None:
            payload["webhook_url"] = webhook_url
        if metadata is not None:
            payload["metadata"] = metadata
        headers = {}
        if idempotency_key:
            headers["Idempotency-Key"] = idempotency_key
        return self._post("/api/v1/payment/create", payload, headers)

    def verify_payment(self, transaction_id):
        """Verify a payment. Returns the data dict with 'status' one of
        PENDING / PROCESSING / COMPLETED / FAILED / CANCELLED / EXPIRED."""
        return self._post("/api/v1/payment/verify", {"transaction_id": transaction_id})

    # -- webhooks ----------------------------------------------------------
    @staticmethod
    def verify_webhook_signature(raw_body, signature_header, secret, tolerance=300):
        """Check an X-Nexuslab-Signature header ('t=<ts>,v1=<hmac>').

        raw_body must be the exact request body bytes. Returns True/False.
        """
        try:
            parts = dict(p.split("=", 1) for p in signature_header.split(","))
            ts = parts["t"]
            v1 = parts["v1"]
        except Exception:
            return False
        if abs(time.time() - int(ts)) > tolerance:
            return False
        if isinstance(raw_body, str):
            raw_body = raw_body.encode()
        expected = hmac.new(
            secret.encode(), ts.encode() + b"." + raw_body, hashlib.sha256
        ).hexdigest()
        return hmac.compare_digest(expected, v1)

    @staticmethod
    def parse_webhook(raw_body):
        """Decode a webhook body (call verify_webhook_signature first)."""
        if isinstance(raw_body, bytes):
            raw_body = raw_body.decode()
        return json.loads(raw_body)
