import logging
import sys
from typing import Optional

# Try to use Uvicorn's formatter if available for consistent styling
try:
    from uvicorn.logging import ColourizedFormatter, DefaultFormatter
    HAS_UVICORN_LOGGING = True
except ImportError:
    HAS_UVICORN_LOGGING = False

def get_logger(name: str = "ombra") -> logging.Logger:
    """
    Get a configured logger that matches Uvicorn's style.
    """
    logger = logging.getLogger(name)
    
    # Only configure if it hasn't been configured yet
    if not logger.handlers:
        handler = logging.StreamHandler(sys.stdout)
        
        if HAS_UVICORN_LOGGING:
            # Use Uvicorn's formatter for colors and style
            # Format: level prefix (colored) + message
            # We use a format string that mimics Uvicorn's default
            formatter = ColourizedFormatter(
                fmt="%(levelprefix)s %(message)s",
                use_colors=True
            )
        else:
            # Fallback if uvicorn is not available
            formatter = logging.Formatter(
                fmt="%(levelname)s:    %(message)s"
            )
            
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        
        # Default level
        logger.setLevel(logging.INFO)
        
        # Prevent propagation to root logger if we are configuring it here
        # (unless we want double logs with Uvicorn's root handler)
        logger.propagate = False
        
    return logger

# Global instance
logger = get_logger()
