"""
Python logging handler that copies ERROR records from the app loggers (and
unhandled request errors from django.request) into the System Log, so code
that only calls logger.error()/logger.exception() still shows up in admin.
Code with richer context should call system_logs.services.log_event().
"""

import logging

_MODULE_BY_LOGGER = {
    "store": "store",
    "inventory": "inventory",
    "catalog_app": "catalog",
    "django.request": "system",
}


class SystemLogHandler(logging.Handler):
    def emit(self, record: logging.LogRecord) -> None:
        # Never re-log our own output (log_event already wrote it).
        if record.name.startswith("system_logs"):
            return
        try:
            from system_logs.models import SystemLog
            from system_logs.services import log_event

            top = record.name.split(".")[0]
            module = _MODULE_BY_LOGGER.get(record.name) or _MODULE_BY_LOGGER.get(top, "system")
            exc = record.exc_info[1] if record.exc_info else None
            request = getattr(record, "request", None)
            log_event(
                module,
                f"log.{record.name}"[:80],
                record.getMessage(),
                level=SystemLog.LEVEL_ERROR if record.levelno >= logging.ERROR else SystemLog.LEVEL_WARNING,
                reference=getattr(request, "path", "") if request is not None else "",
                exc=exc,
                user=getattr(request, "user", None) if request is not None else None,
            )
        except Exception:  # noqa: BLE001
            self.handleError(record)
