import multiprocessing
import os
from pathlib import Path

# Create logs directory if it doesn't exist
os.makedirs('logs', exist_ok=True)

# Server socket
bind = os.getenv('GUNICORN_BIND', '0.0.0.0:5002')
backlog = 2048

# Worker processes
# Formula: (2 x number_of_cores) + 1
workers = int(os.getenv('GUNICORN_WORKERS', 13))  # Default to 13 workers
worker_class = 'sync'
worker_connections = 1000
timeout = int(os.getenv('GUNICORN_TIMEOUT', 30))
keepalive = 2

# Performance optimizations
worker_tmp_dir = '/dev/shm'  # Use RAM for temporary files
limit_request_line = 4094    # Prevent large request attacks
limit_request_fields = 100   # Limit number of request headers

# Logging
accesslog = 'logs/access.log'
errorlog = 'logs/error.log'
loglevel = os.getenv('LOG_LEVEL', 'debug')

# Process naming
proc_name = 'mold_cost_calculator'

# Server mechanics
daemon = False
pidfile = 'gunicorn.pid'
umask = 0
user = None
group = None
tmp_upload_dir = None

# Server hooks
def on_starting(server):
    # Ensure instance directory exists
    os.makedirs('instance', exist_ok=True)

def on_reload(server):
    pass

def on_exit(server):
    pass

# Request limits
max_requests = 1000
max_requests_jitter = 50

# Worker settings
graceful_timeout = 30
preload_app = True

# Environment variables
raw_env = [
    'FLASK_APP=run.py',
    'FLASK_ENV=production',
    'FLASK_DEBUG=0'
]

# Security settings
trusted_proxies = os.getenv('TRUSTED_PROXY_IPS', '127.0.0.1,::1').split(',')
forwarded_allow_ips = ','.join(ip.strip() for ip in trusted_proxies)
secure_scheme_headers = {
    'X-FORWARDED-PROTOCOL': 'ssl',
    'X-FORWARDED-PROTO': 'https',
    'X-FORWARDED-SSL': 'on'
} 