"""
Winnow Logger Module
Centralized logging configuration for the winnow package.
"""

import logging
import sys
from typing import Optional


def setup_logger(
    name: str = "winnow",
    level: int = logging.INFO,
    log_file: Optional[str] = None,
    format_string: Optional[str] = None
) -> logging.Logger:
    """
    Set up and configure a logger instance.
    
    Parameters
    ----------
    name : str, default="winnow"
        Name of the logger
    level : int, default=logging.INFO
        Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
    log_file : str, optional
        Path to log file. If None, logs only to console.
    format_string : str, optional
        Custom format string for log messages
        
    Returns
    -------
    logging.Logger
        Configured logger instance
        
    Examples
    --------
    >>> from winnow.logger import setup_logger
    >>> logger = setup_logger(level=logging.DEBUG)
    >>> logger.info("This is an info message")
    """
    # Create logger
    logger = logging.getLogger(name)
    logger.setLevel(level)
    
    # Avoid duplicate handlers
    if logger.handlers:
        return logger
    
    # Default format
    if format_string is None:
        format_string = "%(asctime)s | %(levelname)-8s | %(message)s"
    
    formatter = logging.Formatter(format_string, datefmt="%Y-%m-%d %H:%M:%S")
    
    # Console handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(level)
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)
    
    # File handler (optional)
    if log_file:
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(level)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)
    
    return logger


def get_logger(name: str = "winnow") -> logging.Logger:
    """
    Get an existing logger or create a new one with default settings.
    
    Parameters
    ----------
    name : str, default="winnow"
        Name of the logger
        
    Returns
    -------
    logging.Logger
        Logger instance
    """
    logger = logging.getLogger(name)
    
    # If logger has no handlers, set up with defaults
    if not logger.handlers:
        return setup_logger(name)
    
    return logger


# Create default logger instance
logger = setup_logger()


__all__ = ['setup_logger', 'get_logger', 'logger']
