"""
DerashPay Python SDK — single-file, zero-dependency API client.

Requirements: Python 3.7+, standard library only (urllib, hmac, hashlib).

Quick start:
    from derashpay import DerashPay, DerashPayError

    dp = DerashPay('dp_secret_test_...')

    # Direct charge
    tx = dp.create_charge(245000, 'ETB', 'telebirr', idempotency_key='order_123')

    # Hosted checkout — redirect the customer to session['url']
    session = dp.create_checkout_session(245000, 'ETB', 'https://you.com/success')
    return redirect(session['url'])   # Flask / Django / FastAPI
"""
from __future__ import annotations

import hashlib
import hmac
import json
import time
import urllib.error
import urllib.request
from typing import Any, Dict, List, Optional


# ---------------------------------------------------------------------------
# Error class
# ---------------------------------------------------------------------------


class DerashPayError(Exception):
    """Raised when the API returns a non-2xx response or a network error occurs."""

    def __init__(self, code: str, message: str, http_status: int = 0) -> None:
        super().__init__(message)
        #: Machine-readable API error code (e.g. ``"auth_invalid"``).
        self.code        = code
        #: HTTP status code (0 for network-level failures).
        self.http_status = http_status

    def __repr__(self) -> str:
        return f"DerashPayError(code={self.code!r}, message={str(self)!r}, http_status={self.http_status})"


# ---------------------------------------------------------------------------
# Client
# ---------------------------------------------------------------------------


class DerashPay:
    """DerashPay REST API client."""

    def __init__(
        self,
        secret_key: str,
        base_url: str = "https://derashpay.co/api/v1",
        timeout: int = 15,
    ) -> None:
        """
        :param secret_key: Your test or live secret key
                           (``dp_secret_test_…`` / ``dp_secret_live_…``).
        :param base_url:   Override only when self-hosting DerashPay.
        :param timeout:    Request timeout in seconds (default 15).
        """
        self._secret_key = secret_key
        self._base_url   = base_url.rstrip("/")
        self._timeout    = timeout

    # -----------------------------------------------------------------------
    # Public API
    # -----------------------------------------------------------------------

    def ping(self) -> Dict[str, Any]:
        """
        Verify authentication and return the merchant / project context.

        :returns: ``{"ok": True, "merchant_id": …, "project_id": …, "mode": "test"|"live", …}``
        :raises DerashPayError:
        """
        return self._request("GET", "/ping")

    def create_charge(
        self,
        amount: int,
        currency: str,
        psp: str,
        *,
        idempotency_key: Optional[str] = None,
        description: Optional[str] = None,
        customer_email: Optional[str] = None,
        customer_name: Optional[str] = None,
        customer_phone: Optional[str] = None,
        metadata: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """
        Create a direct server-to-server charge.

        Amounts are integers in **minor units** — ETB 1.00 = 100,
        ETB 2 450.00 = 245 000. Never pass floats.

        :param amount:          Integer, minor units (no floats).
        :param currency:        3-letter ISO code: ``ETB``, ``USD``, ``EUR`` …
        :param psp:             Provider code: ``telebirr`` | ``cbe`` | ``cbebirr`` |
                                ``awash`` | ``awashbirr`` | ``dashen`` | ``boa`` |
                                ``boa_card`` | ``zamzam`` | ``commercial`` |
                                ``m_pesa`` | ``stripe`` | ``paypal`` |
                                ``card_generic`` | ``local_banks`` | ``pss_cards``
        :param idempotency_key: Unique per logical charge. Replay with the same key
                                returns the original transaction (no double-charge).
        :param description:     Up to 255 characters.
        :param customer_email:
        :param customer_name:
        :param customer_phone:
        :param metadata:        Dict stored as JSON and returned in webhooks.
        :returns: Transaction object: ``id``, ``status``, ``amount``, ``fee``,
                  ``net``, ``currency``, ``psp``, ``created``, …
        :raises DerashPayError:
        """
        body: Dict[str, Any] = {
            "amount":   amount,
            "currency": currency.upper(),
            "psp":      psp,
        }
        if description:    body["description"]    = description
        if customer_email: body["customer_email"] = customer_email
        if customer_name:  body["customer_name"]  = customer_name
        if customer_phone: body["customer_phone"] = customer_phone
        if metadata:       body["metadata"]       = metadata

        extra: Dict[str, str] = {}
        if idempotency_key:
            extra["Idempotency-Key"] = idempotency_key

        return self._request("POST", "/charges", body, extra)

    def create_checkout_session(
        self,
        amount: int,
        currency: str,
        return_url: str,
        *,
        cancel_url: Optional[str] = None,
        allowed_psps: Optional[List[str]] = None,
        description: Optional[str] = None,
        customer_email: Optional[str] = None,
        customer_name: Optional[str] = None,
        customer_phone: Optional[str] = None,
        idempotency_key: Optional[str] = None,
        metadata: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """
        Create a hosted checkout session.

        Redirect (or open) ``session['url']`` in the customer's browser.
        After payment DerashPay sends them to::

            return_url?cs=cs_…&tx=tx_…&status=succeeded|pending

        After cancel::

            cancel_url?cs=cs_…&status=cancelled

        :param amount:      Minor units.
        :param currency:    3-letter ISO code.
        :param return_url:  Where the browser goes after a successful payment.
        :param cancel_url:  Browser lands here on cancel (optional).
        :param allowed_psps: Limit which banks the customer sees, e.g. ``["telebirr","cbe"]``.
        :returns: Session object: ``id``, ``url``, ``status``, ``expires_at``, …
        :raises DerashPayError:
        """
        body: Dict[str, Any] = {
            "amount":     amount,
            "currency":   currency.upper(),
            "return_url": return_url,
        }
        if cancel_url:     body["cancel_url"]     = cancel_url
        if description:    body["description"]    = description
        if customer_email: body["customer_email"] = customer_email
        if customer_name:  body["customer_name"]  = customer_name
        if customer_phone: body["customer_phone"] = customer_phone
        if allowed_psps:   body["allowed_psps"]   = allowed_psps
        if metadata:       body["metadata"]       = metadata

        extra: Dict[str, str] = {}
        if idempotency_key:
            extra["Idempotency-Key"] = idempotency_key

        return self._request("POST", "/checkout_sessions", body, extra)

    # -----------------------------------------------------------------------
    # Static / webhook verification
    # -----------------------------------------------------------------------

    @staticmethod
    def verify_webhook(
        payload: "bytes | str",
        signature_header: str,
        endpoint_secret: str,
        tolerance_seconds: int = 300,
    ) -> bool:
        """
        Verify the ``X-DerashPay-Signature`` header on an incoming webhook.

        Call this **before** parsing or acting on the payload.
        Returns ``True`` only when the HMAC is valid **and** the timestamp
        is within *tolerance_seconds* of now (prevents replay attacks).

        Flask example::

            @app.post("/webhook")
            def webhook():
                ok = DerashPay.verify_webhook(
                    request.get_data(),                          # raw bytes
                    request.headers["X-DerashPay-Signature"],
                    "whsec_...",
                )
                if not ok:
                    abort(400)
                event = request.get_json(force=True)
                if event["type"] == "transaction.succeeded":
                    ...
                return "", 200

        Django example::

            @csrf_exempt
            def webhook(request):
                ok = DerashPay.verify_webhook(
                    request.body,
                    request.META.get("HTTP_X_DERASHPAY_SIGNATURE", ""),
                    "whsec_...",
                )
                if not ok:
                    return HttpResponse(status=400)
                event = json.loads(request.body)
                return HttpResponse(status=200)

        :param payload:            Raw request body — read **before** ``json.loads``.
        :param signature_header:   Value of ``X-DerashPay-Signature`` header.
        :param endpoint_secret:    Secret shown next to your URL in Settings → Webhooks.
        :param tolerance_seconds:  Reject events older than this (default 300 s = 5 min).
        :returns: ``True`` if the signature is valid and fresh.
        """
        import re
        m = re.match(r"^t=(\d+),v1=([a-f0-9]+)$", signature_header or "")
        if not m:
            return False

        ts_str, given = m.group(1), m.group(2)

        if isinstance(payload, str):
            payload = payload.encode("utf-8")

        msg      = (ts_str + "." + payload.decode("utf-8")).encode("utf-8")
        expected = hmac.new(
            endpoint_secret.encode("utf-8"),
            msg,
            hashlib.sha256,
        ).hexdigest()

        sig_ok = hmac.compare_digest(given, expected)
        fresh  = abs(time.time() - int(ts_str)) < tolerance_seconds
        return sig_ok and fresh

    # -----------------------------------------------------------------------
    # Internal
    # -----------------------------------------------------------------------

    def _request(
        self,
        method: str,
        path: str,
        body: Optional[Dict[str, Any]] = None,
        extra_headers: Optional[Dict[str, str]] = None,
    ) -> Dict[str, Any]:
        url     = self._base_url + path
        payload = json.dumps(body, ensure_ascii=False).encode("utf-8") if body is not None else None

        headers: Dict[str, str] = {
            "Authorization": "Bearer " + self._secret_key,
            "Accept":        "application/json",
        }
        if payload is not None:
            headers["Content-Type"] = "application/json"
        if extra_headers:
            headers.update(extra_headers)

        req = urllib.request.Request(
            url,
            data=payload,
            headers=headers,
            method=method,
        )
        try:
            with urllib.request.urlopen(req, timeout=self._timeout) as resp:
                return json.loads(resp.read().decode("utf-8"))

        except urllib.error.HTTPError as exc:
            raw = exc.read().decode("utf-8", errors="replace")
            try:
                err_obj = json.loads(raw).get("error", {})
                code    = err_obj.get("code",    "unknown_error")
                msg     = err_obj.get("message", f"HTTP {exc.code}")
            except (json.JSONDecodeError, AttributeError):
                code = "invalid_response"
                msg  = f"HTTP {exc.code}: {raw[:200]}"
            raise DerashPayError(code, msg, exc.code) from None

        except urllib.error.URLError as exc:
            raise DerashPayError(
                "network_error",
                f"Could not reach DerashPay API: {exc.reason}",
            ) from None
