"""
Receiving Playmez webhooks (Python 3.8+). Copy into your backend.

Playmez posts JSON to the URL you set with PUT /partner/webhook and signs every delivery:
    Playmez-Signature: v1=<hex HMAC-SHA256 of "<Playmez-Timestamp>.<raw body>">
Verify against the raw bytes, answer 2xx within 10 seconds, and treat event["id"] as an
idempotency key: failed deliveries are retried with the same id.
"""
import hashlib
import hmac
import os
import time

SECRET = os.environ.get("PLAYMEZ_WEBHOOK_SECRET", "")  # whsec_…, shown once when you set the URL
TOLERANCE_SECONDS = 300


def verify_playmez_webhook(raw_body: bytes, signature: str, timestamp: str, secret: str = SECRET, now: float = None) -> bool:
    """True when the delivery was signed with your secret and is recent."""
    if not secret or not signature or not timestamp:
        return False
    now = time.time() if now is None else now
    try:
        if abs(now - int(timestamp)) > TOLERANCE_SECONDS:
            return False
    except ValueError:
        return False
    expected = hmac.new(secret.encode(), f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest()
    given = [p.strip()[3:] for p in signature.split(",") if p.strip().startswith("v1=")]
    return any(hmac.compare_digest(g, expected) for g in given)


# Flask example. request.get_data() is the raw body; do not re-serialise request.json.
#
#   @app.post("/playmez/webhook")
#   def playmez_webhook():
#       if not verify_playmez_webhook(request.get_data(), request.headers.get("Playmez-Signature", ""), request.headers.get("Playmez-Timestamp", "")):
#           abort(401)
#       event = request.get_json()  # { id, type, createdAt, partner: { id, slug }, data }
#       if already_handled(event["id"]):
#           return "", 200
#       if event["type"] == "player.result":
#           record_result(event["data"]["player"]["externalUserId"], event["data"])
#       return "", 200
