from __future__ import annotations

import logging
from typing import Any

from pulselog.logger import Logger


class PulseHandler(logging.Handler):
    """Bridge between Python's standard ``logging`` module and pulselog.

    Usage::

        import logging
        from pulselog.handler import PulseHandler

        handler = PulseHandler("my-app", dashboard=True)
        logging.getLogger().addHandler(handler)
        logging.info("this appears in the pulselog dashboard")
    """

    def __init__(self, name: str = "root", **kwargs: Any) -> None:
        super().__init__()
        self._logger = Logger(name, **kwargs)

    def emit(self, record: logging.LogRecord) -> None:
        """Forward a stdlib log record to pulselog.

        Args:
            record: Standard LogRecord from the stdlib logging framework.
        """
        level_map = {
            logging.DEBUG:    self._logger.debug,
            logging.INFO:     self._logger.info,
            logging.WARNING:  self._logger.warning,
            logging.ERROR:    self._logger.error,
            logging.CRITICAL: self._logger.critical,
        }
        fn = level_map.get(record.levelno, self._logger.info)
        try:
            fn(self.format(record))
        except Exception:
            self.handleError(record)
