"""SSE (Server-Sent Events) endpoint."""

from __future__ import annotations

import asyncio
import json

from aiohttp import web


async def sse_events(request: web.Request) -> web.StreamResponse:
    """Stream Server-Sent Events for task status changes and log updates."""
    from dobby.core.api import EventBus

    event_bus: EventBus | None = request.app.get("event_bus")
    if event_bus is None:
        raise web.HTTPServiceUnavailable(reason="Event bus not available")

    response = web.StreamResponse(
        status=200,
        reason="OK",
        headers={
            "Content-Type": "text/event-stream",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no",
        },
    )
    await response.prepare(request)

    queue = event_bus.subscribe()
    try:
        while True:
            try:
                payload = await asyncio.wait_for(queue.get(), timeout=30)
                event_type = payload["event"]
                data = json.dumps(payload["data"])
                await response.write(
                    f"event: {event_type}\ndata: {data}\n\n".encode()
                )
            except TimeoutError:
                # Send keepalive comment
                await response.write(b": keepalive\n\n")
            except ConnectionResetError:
                break
    finally:
        event_bus.unsubscribe(queue)

    return response
