"""Optional FastAPI adapter (requires the ``[fastapi]`` extra).

One line in a route handler turns an :class:`SSEStreamService` into a
``StreamingResponse``, mapping the cap-exceeded case to a 429 with a
``Retry-After`` header.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from mgf.livepush._errors import CapExceededError

if TYPE_CHECKING:
    from fastapi import Request
    from fastapi.responses import StreamingResponse

    from mgf.livepush._sse import SSEStreamService

__all__ = ["sse_streaming_response"]


async def sse_streaming_response(
    service: SSEStreamService,
    request: Request,
    *,
    channel: str,
    slot_key: str,
) -> StreamingResponse:
    """Open an SSE stream and wrap it in a FastAPI ``StreamingResponse``.

    Raises ``HTTPException(429)`` with ``Retry-After: 5`` when the
    per-key slot cap is exhausted.
    """
    from fastapi import HTTPException
    from fastapi.responses import StreamingResponse

    try:
        stream = await service.open_stream(
            channel=channel,
            slot_key=slot_key,
            is_disconnected=request.is_disconnected,
        )
    except CapExceededError as exc:
        raise HTTPException(status_code=429, detail=str(exc), headers={"Retry-After": "5"}) from exc
    return StreamingResponse(stream.body, media_type="text/event-stream", headers=stream.headers)
