"""Qt bridge for viewer logging."""

from __future__ import annotations

import logging

from PySide6 import QtCore


class _QtLogRelay(QtCore.QObject):
    """QObject wrapper used to forward logging records across threads."""

    message_logged = QtCore.Signal(str, int)


class QtLogHandler(logging.Handler):
    """Logging handler that forwards formatted records into Qt widgets."""

    def __init__(self, *, level: int = logging.NOTSET):
        super().__init__(level=level)
        self.relay = _QtLogRelay()
        self.setFormatter(
            logging.Formatter(
                fmt="%(asctime)s %(levelname)s %(name)s: %(message)s",
                datefmt="%H:%M:%S",
            )
        )

    def emit(self, record: logging.LogRecord) -> None:
        try:
            message = self.format(record)
        except Exception:
            self.handleError(record)
            return
        self.relay.message_logged.emit(message, int(record.levelno))


__all__ = ["QtLogHandler"]
