import logging
from typing import Any

from .base import MetricsLogger


class ConsoleLogger(MetricsLogger):
    """Console logger implementation using Python's logging module."""

    def __init__(self, name: str | None = None, level: int = logging.INFO):
        """Initialize the console logger.

        Args:
            name: Logger name (default: None, uses root logger)
            level: Logging level (default: INFO)

        """
        self.logger = logging.getLogger(name)
        self.logger.setLevel(level)

        if not self.logger.handlers:
            handler = logging.StreamHandler()
            handler.setLevel(level)
            formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
            handler.setFormatter(formatter)
            self.logger.addHandler(handler)

    def log_metrics(self, metrics: dict[str, Any], step: int, prefix: str = "") -> None:
        """Log metrics to console.

        Args:
            metrics: Dictionary of metric names to values
            step: Current step/iteration number
            prefix: Optional prefix for metric names

        """
        metrics_str = " | ".join(f"{k}: {v:.4f}" for k, v in metrics.items())
        if prefix:
            metrics_str = f"[{prefix}] {metrics_str}"
        msg = f"Step {step}: {metrics_str}"
        self.logger.info(msg)

    def close(self) -> None:
        """No cleanup needed for console logger."""
