"""
Armory SDK Logger

Provides a unified logging interface for the Armory SDK.
Users can configure log level via:
- Environment variable: ARMORY_LOG_LEVEL (DEBUG, INFO, WARNING, ERROR)
- Programmatically: armory.set_log_level("DEBUG")
"""

import logging
import os
import sys

# Create the armory logger
logger = logging.getLogger("armory")

# Default format
_DEFAULT_FORMAT = "[armory] %(levelname)s: %(message)s"
_DEBUG_FORMAT = "[armory] %(levelname)s [%(filename)s:%(lineno)d]: %(message)s"


def _setup_logger():
    """Setup the logger with default configuration"""
    # Don't add handlers if they already exist
    if logger.handlers:
        return

    # Get log level from environment
    level_str = os.getenv("ARMORY_LOG_LEVEL", "INFO").upper()
    level = getattr(logging, level_str, logging.INFO)

    logger.setLevel(level)

    # Create console handler
    handler = logging.StreamHandler(sys.stderr)
    handler.setLevel(level)

    # Use debug format for DEBUG level
    fmt = _DEBUG_FORMAT if level == logging.DEBUG else _DEFAULT_FORMAT
    formatter = logging.Formatter(fmt)
    handler.setFormatter(formatter)

    logger.addHandler(handler)

    # Prevent propagation to root logger
    logger.propagate = False


def set_log_level(level: str):
    """
    Set the log level for the Armory SDK.

    Args:
        level: Log level string - "DEBUG", "INFO", "WARNING", "ERROR"

    Example:
        import armory
        armory.set_log_level("DEBUG")
    """
    level_value = getattr(logging, level.upper(), logging.INFO)
    logger.setLevel(level_value)
    for handler in logger.handlers:
        handler.setLevel(level_value)
        # Update format if switching to/from DEBUG
        if level_value == logging.DEBUG:
            handler.setFormatter(logging.Formatter(_DEBUG_FORMAT))
        else:
            handler.setFormatter(logging.Formatter(_DEFAULT_FORMAT))


def get_logger(name: str = None) -> logging.Logger:
    """
    Get a child logger for a specific module.

    Args:
        name: Optional name for the child logger

    Returns:
        Logger instance
    """
    if name:
        return logger.getChild(name)
    return logger


# Setup logger on import
_setup_logger()
