"""
Gunicorn configuration file that reads settings from .env via pydantic-settings
"""
import sys
from loguru import logger
from bfabric_web_apps.utils.config import settings

# Server socket
bind = f"{settings.HOST}:{settings.PORT}"

# Worker processes
workers = settings.GUNICORN_WORKERS
threads = settings.GUNICORN_THREADS
worker_class = "sync"

# Timeouts
timeout = 120
keepalive = 5

# Logging
# Only log access in debug mode to reduce noise in production
accesslog = "-" if settings.DEBUG else None  # Log to stdout in debug, disabled in production
errorlog = "-"   # Always log errors to stderr
loglevel = "debug" if settings.DEBUG else "info"

# Process naming
proc_name = "bfabric-web-app"

# Server mechanics
daemon = False
pidfile = None
user = None
group = None

# Configure Loguru based on DEBUG setting
def post_fork(server, worker):
    """Configure Loguru after worker fork"""
    log_level = "DEBUG" if settings.DEBUG else "INFO"
    logger.remove()  # Remove default handler
    logger.add(
        sys.stderr,
        level=log_level,
        format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
    )