"""Verify gaiia webhooks in a Flask endpoint.

    pip install flask gaiia
    GAIIA_WEBHOOK_SECRET=whsec_... flask --app examples/webhook_flask.py run
"""

from __future__ import annotations

import json
import os

from flask import Flask, abort, request

from gaiia import WebhookSignatureError, verify_webhook_signature

app = Flask(__name__)
SECRET = os.environ["GAIIA_WEBHOOK_SECRET"]


@app.post("/gaiia/webhook")
def webhook() -> tuple[str, int]:
    raw = request.get_data()
    try:
        verify_webhook_signature(
            header_value=request.headers.get("X-Gaiia-Webhook-Signature", ""),
            raw_body=raw,
            secret=SECRET,
        )
    except WebhookSignatureError as e:
        abort(400, description=str(e))

    event = json.loads(raw)
    app.logger.info("gaiia event: %s", event.get("type"))
    return "", 204
