"""Stdlib logging bridge — use snaplog as a handler for the logging module."""

import logging
from snaplog.logger import get_logger


class SnaplogHandler(logging.Handler):
    """Bridge handler that routes stdlib logging through snaplog.

    Usage:
        import logging
        from snaplog import SnaplogHandler

        handler = SnaplogHandler()
        logging.root.addHandler(handler)
        logging.info("This becomes structured JSON")
    """

    _level_map = {
        logging.DEBUG: "debug",
        logging.INFO: "info",
        logging.WARNING: "warning",
        logging.ERROR: "error",
        logging.CRITICAL: "critical",
    }

    def __init__(self, name: str = "stdlib", **kwargs):
        super().__init__(**kwargs)
        self._log = get_logger(name)

    def emit(self, record: logging.LogRecord) -> None:
        try:
            level = self._level_map.get(record.levelno, "info")
            msg = self.format(record)
            kwargs = {"logger": record.name}
            if record.exc_info and record.exc_info[0]:
                kwargs["exc_type"] = record.exc_info[0].__name__
                kwargs["exc_msg"] = str(record.exc_info[1])
            if record.pathname:
                kwargs["file"] = record.pathname.split("/")[-1]
            if record.lineno:
                kwargs["line"] = record.lineno
            if record.funcName:
                kwargs["func"] = record.funcName
            self._log._log(level, msg, _skip_frames=2, **kwargs)
        except Exception:
            self.handleError(record)
