import asyncio
import logging
from datetime import datetime, timezone

from .ws_manager import manager


class WSLogHandler(logging.Handler):
    """Posílá log záznamy přes WebSocket všem připojeným klientům /ws/logs."""

    def emit(self, record: logging.LogRecord) -> None:
        try:
            loop = asyncio.get_running_loop()
        except RuntimeError:
            return
        ts = datetime.fromtimestamp(record.created, tz=timezone.utc).strftime("%H:%M:%S")
        msg = {
            "ts": ts,
            "level": record.levelname,
            "logger": record.name.split(".")[-1],
            "msg": record.getMessage(),
        }
        loop.call_soon_threadsafe(
            lambda: asyncio.ensure_future(manager.broadcast_log(msg))
        )
