"""FlowPayra Lite webhook and return-URL signature verification for Python 3.8+, standard library only.

    from flowpay import verify_webhook, verify_return_url

    # Flask: verify the raw body, before any JSON parsing.
    @app.post("/flowpay/webhook")
    def webhook():
        if not verify_webhook(SECRET, request.headers.get("FlowPay-Signature", ""), request.get_data()):
            abort(400)
        event = json.loads(request.get_data())
        # ... handle event["type"] idempotently by event["id"]
        return "", 200

    # Return page: show the outcome; fulfil from the webhook or GET /v1/orders/{id}.
    verified = verify_return_url(SECRET, request.url)   # {"order_id": ..., "status": ...} or None
"""

import hashlib
import hmac
import re
import time
from urllib.parse import parse_qs, urlsplit

_HEX = re.compile(r"^[0-9a-fA-F]*$")


def _mac(secret: str, data: bytes) -> bytes:
    return hmac.new(secret.encode("utf-8"), data, hashlib.sha256).digest()


def verify_webhook(secret: str, header: str, raw_body: bytes, now: int = None, tolerance: int = 300) -> bool:
    """`FlowPay-Signature: t=<unix seconds>,v1=<hex>` over b"<t>.<raw body>"; any v1 may match (rotation)."""
    if not secret or not header:
        return False
    now = int(time.time()) if now is None else now
    ts, sigs = None, []
    for part in header.split(","):
        key, sep, value = part.strip().partition("=")
        if not sep:
            continue
        if key == "t" and value.isdigit():
            ts = int(value)
        elif key == "v1":
            if not _HEX.match(value) or len(value) % 2:
                return False
            sigs.append(bytes.fromhex(value))
    if ts is None or not sigs or abs(now - ts) > tolerance:
        return False
    if isinstance(raw_body, str):
        raw_body = raw_body.encode("utf-8")
    expected = _mac(secret, str(ts).encode() + b"." + raw_body)
    return any(hmac.compare_digest(s, expected) for s in sigs)


def verify_return_url(secret: str, url: str, now: int = None, max_age: int = 600):
    """sig = hex(HMAC-SHA256(secret, "<order_id>.<status>.<ts>")) over the last occurrence of each parameter, and
    ts within max_age of now. Returns {"order_id", "status"} or None."""
    query = parse_qs(urlsplit(url).query, keep_blank_values=True)
    last = {k: v[-1] for k, v in query.items()}
    order_id, status, ts, sig = (last.get(k) for k in ("order_id", "status", "ts", "sig"))
    if not (secret and order_id and status and ts and sig) or not ts.isdigit() or not re.fullmatch(r"[0-9a-fA-F]{64}", sig):
        return None
    now = int(time.time()) if now is None else now
    if abs(now - int(ts)) > max_age:
        return None
    expected = _mac(secret, f"{order_id}.{status}.{ts}".encode("utf-8"))
    return {"order_id": order_id, "status": status} if hmac.compare_digest(bytes.fromhex(sig), expected) else None
