"""Simple logging wrapper for SD-API."""

from __future__ import annotations

import logging
import sys
from typing import Optional

# Module-level logger — created lazily
_logger: Optional[logging.Logger] = None


def get_logger(name: str | None = None) -> logging.Logger:
    """Return (or create) the SDK logger.

    Parameters
    ----------
    name : str, optional
        Sub-logger name. When None, returns the root ``sd_api`` logger.

    Returns
    -------
    logging.Logger
    """
    global _logger
    if _logger is None:
        _logger = logging.getLogger("sd_api")
        _logger.setLevel(logging.INFO)
        if not _logger.handlers:
            handler = logging.StreamHandler(sys.stderr)
            handler.setFormatter(
                logging.Formatter("[%(levelname)s] %(name)s: %(message)s")
            )
            _logger.addHandler(handler)
    if name:
        return logging.getLogger(f"sd_api.{name}")
    return _logger


def set_log_level(level: str) -> None:
    """Change the SDK log level at runtime.

    Parameters
    ----------
    level : str
        One of DEBUG, INFO, WARNING, ERROR, CRITICAL.
    """
    logger = get_logger()
    logger.setLevel(getattr(logging, level.upper(), logging.INFO))
