import logging


class ErrorLogRecord(logging.LogRecord):
    error_app_id: str
    error_code: str
    error_fault: str
    error_category: str
    error_retryable: bool
    error_throttled: bool
    error_refreshable: bool
    error_hint: str


class ErrorLogFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        message = super().format(record)

        if isinstance(record, ErrorLogRecord):
            extras = {
                "error_app_id": record.error_app_id,
                "error_code": record.error_code,
                "error_fault": record.error_fault,
                "error_category": record.error_category,
                "error_retryable": record.error_retryable,
                "error_throttled": record.error_throttled,
                "error_refreshable": record.error_refreshable,
                "error_hint": record.error_hint,
            }
            message = f"{message}\n Details: {extras}"

        return message


def create_error_logger(logger_name: str) -> logging.Logger:
    """Create a error logger"""
    error_logger = logging.getLogger(logger_name)

    # Only add handler if one doesn't already exist
    if not error_logger.handlers:
        handler = logging.StreamHandler()
        handler.setFormatter(
            ErrorLogFormatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        )
        error_logger.addHandler(handler)

    # Prevent logs from propagating to parent loggers (which might have their own handlers)
    error_logger.propagate = False
    error_logger.setLevel(logging.ERROR)

    return error_logger
