"""PayVAN request signing and webhook verification (Python 3.8+, stdlib only).

Run this file directly to check it against the reference vectors from
https://docs.payvan.net/#auth-reference.
"""

import hashlib
import hmac
import time
import uuid


def sign_request(secret: str, method: str, path: str, shop_id: str,
                 body: bytes, request_id: str = None, timestamp: int = None) -> dict:
    """Return the four authentication headers for one API request.

    `path` includes the query string, if any. `body` must be the exact bytes
    you send: sign first, then send the same bytes without re-serializing.
    """
    request_id = request_id or str(uuid.uuid4())
    timestamp = int(time.time()) if timestamp is None else timestamp
    message = "\n".join([
        "v1",
        method.upper(),
        path,
        str(shop_id),
        request_id,
        str(timestamp),
        hashlib.sha256(body).hexdigest(),
    ])
    signature = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest()
    return {
        "X-SHOP-ID": str(shop_id),
        "X-REQUEST-ID": request_id,
        "X-REQUEST-TIMESTAMP": str(timestamp),
        "X-REQUEST-SIGNATURE": "v1=" + signature,
    }


def verify_webhook(secrets: list, url: str, headers: dict, body: bytes,
                   max_age: int = 300) -> bool:
    """Check a webhook from PayVAN.

    `secrets` is every key you currently hold (two during a key rotation).
    `url` is the full notification URL PayVAN posted to, exactly as configured.
    `headers` keys are matched case-insensitively.
    """
    h = {k.lower(): v for k, v in headers.items()}
    try:
        timestamp = int(h["x-webhook-timestamp"])
    except (KeyError, ValueError):
        return False
    message = "\n".join([
        "v1-webhook",
        "POST",
        url,
        h.get("x-shop-id", ""),
        h.get("x-webhook-id", ""),
        str(timestamp),
        hashlib.sha256(body).hexdigest(),
    ]).encode()

    # The header may carry several signatures: "v1-webhook=<a>,v1-webhook=<b>".
    received = []
    for part in h.get("x-webhook-signature", "").split(","):
        label, _, value = part.strip().partition("=")
        if label == "v1-webhook" and value:
            received.append(value.strip())

    ok = any(
        hmac.compare_digest(hmac.new(s.encode(), message, hashlib.sha256).hexdigest(), sig)
        for s in secrets for sig in received
    )
    return ok and abs(time.time() - timestamp) <= max_age


if __name__ == "__main__":
    SECRET = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"

    body = b'{"OrderId":"A-1001","Amount":"1499.00","Currency":"USD"}'
    headers = sign_request(SECRET, "POST", "/v1/payments", "1001", body,
                           request_id="2f0f2b1c-6c4b-4a1e-9a3d-8b7f0c5e1d42",
                           timestamp=1789732800)
    expected = "v1=429303de742eaefaa085170c872d03d4d9f40ca3457c5507dab76ebaadb6bfda"
    assert headers["X-REQUEST-SIGNATURE"] == expected, headers
    print("request signature: OK")

    hook = b'{"Event":"Payment","TransactionId":"3554","OrderId":"A-1001","Amount":"1499.00","Currency":"USD"}'
    hook_headers = {
        "X-SHOP-ID": "1001",
        "X-WEBHOOK-ID": "wh_7f3a9c",
        "X-WEBHOOK-TIMESTAMP": "1789732860",
        "X-WEBHOOK-SIGNATURE":
            "v1-webhook=8d1f0f9a2207241e640bd28aef00de33aca990e7087b06df38a09917d995b4b6",
    }
    # max_age is disabled here only because the vector has a fixed timestamp.
    assert verify_webhook([SECRET], "https://shop.example/hooks/payvan", hook_headers, hook,
                          max_age=10**10)
    print("webhook signature: OK")
