import logging

import zmq
from fastapi import APIRouter
from fastapi.responses import StreamingResponse
from zmq.asyncio import Context

from control_backend.core.config import settings

logger = logging.getLogger(__name__)

router = APIRouter()


# DO NOT LOG INSIDE THIS FUNCTION
@router.get("/logs/stream")
async def log_stream():
    """
    Server-Sent Events (SSE) endpoint for real-time log streaming.

    Subscribes to the internal ZMQ logging topic and forwards log records to the client.
    Allows the frontend to display live logs from the backend.

    :return: A StreamingResponse yielding SSE data.
    """
    context = Context.instance()
    socket = context.socket(zmq.SUB)

    for level in logging.getLevelNamesMapping():
        socket.subscribe(topic=level)

    socket.connect(settings.zmq_settings.internal_sub_address)

    async def gen():
        while True:
            _, message = await socket.recv_multipart()
            message = message.decode().strip()
            yield f"data: {message}\n\n"

    return StreamingResponse(gen(), media_type="text/event-stream")
