"""One-time logging configuration for all fh_saas modules."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/06_utils_log.ipynb.

# %% auto #0
__all__ = ['configure_logging']

# %% ../nbs/06_utils_log.ipynb #376c1fd7
import os
import logging
import logging.handlers
from pathlib import Path

# %% ../nbs/06_utils_log.ipynb #c8a3de62
def configure_logging(
    log_file: str = None,
    level: str = None,
    max_bytes: int = 10_000_000,
    backup_count: int = 5,
):
    """Configure logging for all fh_saas modules - call once at app startup."""
    # Resolve level from env var or parameter
    if level is None:
        level = os.getenv('FH_SAAS_LOG_LEVEL', 'WARNING')
    log_level = getattr(logging, level.upper(), logging.WARNING)
    
    # Resolve log file from env var or parameter
    if log_file is None:
        log_file = os.getenv('FH_SAAS_LOG_FILE')
    
    # Create formatter
    formatter = logging.Formatter(
        '%(asctime)s | %(name)s | %(levelname)s | %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    # Create handlers
    handlers = []
    handlers.append(logging.StreamHandler())  # Always console
    
    # File handler (if specified)
    if log_file:
        Path(log_file).parent.mkdir(parents=True, exist_ok=True)
        handlers.append(logging.handlers.RotatingFileHandler(
            log_file, maxBytes=max_bytes, backupCount=backup_count
        ))
    
    # Apply formatter to all handlers
    for handler in handlers:
        handler.setFormatter(formatter)
    
    # Configure fh_saas package logger
    package_logger = logging.getLogger('fh_saas')
    package_logger.setLevel(log_level)
    package_logger.handlers = handlers
    package_logger.propagate = False
