import logging
import sys
import socket
import warnings
from datetime import datetime

# Get hostname once at module load
HOSTNAME = socket.gethostname()

# Flag to ensure logging is only configured once
_logging_configured = False

def configure_logging():
    """
    Configure logging with timestamps and hostname for all Featrix modules.
    This should be called early in the process before any other modules
    that might call logging.basicConfig().
    """
    global _logging_configured
    
    if _logging_configured:
        return
    
    # Force reconfiguration by clearing existing handlers
    root_logger = logging.getLogger()
    if root_logger.handlers:
        for handler in root_logger.handlers:
            root_logger.removeHandler(handler)
    
    # Set up comprehensive logging configuration with timestamps, hostname, thread ID, and PID
    # Format: timestamp [HOSTNAME] [LEVEL] [PID] [THREAD] logger_name: message
    # %(levelname)-8s provides fixed-width severity (padded to 8 chars, left-aligned)
    # %(process)d shows the process ID to distinguish main vs workers
    logging.basicConfig(
        level=logging.INFO,
        format=f'%(asctime)s [{HOSTNAME}] [%(levelname)-8s] [PID:%(process)d] [%(threadName)s] %(name)-45s: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S',
        stream=sys.stdout,
        force=True  # Force reconfiguration even if already configured
    )
    
    _logging_configured = True
    
    # Suppress Pydantic protected namespace warnings (we've configured all models with protected_namespaces=())
    warnings.filterwarnings('ignore', message='.*Field.*has conflict with protected namespace.*model_.*', category=UserWarning)
    
    # Log that logging was configured
    logger = logging.getLogger(__name__)
    logger.info(f"🕐 Featrix logging configured on {HOSTNAME} at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

# Auto-configure logging when this module is imported
configure_logging() 