"""SSE router for filesystem change events."""

import asyncio
import logging

from fastapi import APIRouter, Depends
from fastapi.responses import StreamingResponse

from hangar.services.watcher import WatcherService

logger = logging.getLogger(__name__)

router = APIRouter(tags=["watch"])

# Lazy-initialized watcher (needs project_path from dependencies)
_watcher_service: WatcherService | None = None


def set_watcher_service(service: WatcherService) -> None:
    global _watcher_service
    _watcher_service = service


def get_watcher_service() -> WatcherService:
    if _watcher_service is None:
        raise RuntimeError("WatcherService not initialized")
    return _watcher_service


@router.get("/api/watch")
async def watch_events(
    service: WatcherService = Depends(get_watcher_service),
) -> StreamingResponse:
    """SSE endpoint that streams file change events to the frontend."""

    async def event_stream():
        queue = service.register_client()
        try:
            # Send initial keepalive
            yield ": connected\n\n"

            while True:
                try:
                    message = await asyncio.wait_for(queue.get(), timeout=30.0)
                    yield message
                except asyncio.TimeoutError:
                    # Send keepalive comment to prevent connection timeout
                    yield ": keepalive\n\n"
        except asyncio.CancelledError:
            pass
        finally:
            service.deregister_client(queue)

    return StreamingResponse(
        event_stream(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no",
        },
    )
