"""Plugin logging utilities.

Provides a ``get_plugin_logger`` helper that creates a pre-configured
logger for plugins with automatic context injection (plugin name,
experiment_id, etc.).

Usage in a plugin::

    from mld_sdk.logging import get_plugin_logger

    logger = get_plugin_logger("my-plugin")
    logger.info("Processing experiment", extra={"experiment_id": 42})
"""

import logging
from typing import Any


class PluginLoggerAdapter(logging.LoggerAdapter):
    """Logger adapter that injects plugin context into every log record.

    Automatically adds ``plugin`` to the extra dict so that platform
    log formatters (JSON and dev) can include it.
    """

    def process(
        self, msg: str, kwargs: dict[str, Any]
    ) -> tuple[str, dict[str, Any]]:
        extra = kwargs.get("extra", {})
        # Merge adapter defaults (plugin name) with per-call extras
        merged = {**self.extra, **extra}
        kwargs["extra"] = merged
        return msg, kwargs


def get_plugin_logger(plugin_name: str) -> PluginLoggerAdapter:
    """Get a logger pre-configured with the plugin's name.

    The returned logger automatically adds ``plugin=<name>`` to every
    log record, which the platform's structured formatters pick up.

    Args:
        plugin_name: The plugin's registered name (e.g. ``"drp"``).

    Returns:
        A :class:`PluginLoggerAdapter` wrapping ``logging.getLogger(f"mld.plugin.{plugin_name}")``.
    """
    base_logger = logging.getLogger(f"mld.plugin.{plugin_name}")
    return PluginLoggerAdapter(base_logger, {"plugin": plugin_name})
