"""FastAPI / Starlette adapter.

Usage with FastAPI::

    @app.post("/pillar")
    async def pillar_endpoint(request: Request):
        return await pillar.handle_fastapi(request)

Or simply pass the Starlette ``Request`` to ``pillar.handle()`` after
extracting body/headers — the ``Pillar.handle`` method works with raw
bytes + headers.
"""
from __future__ import annotations

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from pillar._client import Pillar


async def handle_fastapi_request(pillar: Pillar, request: Any) -> Any:
    """Handle a FastAPI/Starlette ``Request`` and return a ``JSONResponse``."""
    from starlette.responses import JSONResponse

    body = await request.body()
    headers = {
        "X-Pillar-Signature": request.headers.get("x-pillar-signature", ""),
    }
    result, status_code = await pillar.handle(body, headers)
    return JSONResponse(result, status_code=status_code)
