"""Flask handler adapter.

Usage::

    app.route("/pillar", methods=["POST"])(pillar.flask_handler())
"""
from __future__ import annotations

import asyncio
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from pillar._client import Pillar


def make_flask_handler(pillar: Pillar) -> Any:
    """Return a Flask handler function wired to *pillar*."""

    def handler() -> Any:
        from flask import Response, request

        body = request.get_data()
        headers = {
            "X-Pillar-Signature": request.headers.get("X-Pillar-Signature", ""),
        }
        result, status_code = asyncio.run(pillar.handle(body, headers))

        import json
        return Response(
            json.dumps(result),
            status=status_code,
            content_type="application/json",
        )

    return handler
