import logging
from flask import request

logger = logging.getLogger(__name__)


def get_client_ip():
    """Get the real IP address of the client"""
    # Debug logging
    logger.info(f"Headers - X-Real-IP: {request.headers.get('X-Real-IP')}, "
                f"X-Forwarded-For: {request.headers.get('X-Forwarded-For')}, "
                f"Remote-Addr: {request.remote_addr}")
    
    # Try X-Real-IP first (set by nginx)
    if request.headers.get('X-Real-IP'):
        return request.headers.get('X-Real-IP')
    # Then X-Forwarded-For
    elif request.headers.get('X-Forwarded-For'):
        # X-Forwarded-For can contain multiple IPs, take the first one
        return request.headers.get('X-Forwarded-For').split(',')[0].strip()
    # Fallback to remote_addr
    else:
        return request.remote_addr