"""
Módulo de logging estructurado para RoadFY.
"""
import logging
import sys
import json
from datetime import datetime
from pathlib import Path
from app.config import Config

class StructuredFormatter(logging.Formatter):
    """Formatter que produce logs estructurados en formato JSON."""
    
    def format(self, record):
        log_data = {
            'timestamp': datetime.utcnow().isoformat(),
            'level': record.levelname,
            'logger': record.name,
            'message': record.getMessage(),
            'module': record.module,
            'function': record.funcName,
            'line': record.lineno,
        }
        
        # Agregar información adicional si está disponible
        if hasattr(record, 'user_id'):
            log_data['user_id'] = record.user_id
        if hasattr(record, 'user_email'):
            log_data['user_email'] = record.user_email
        if hasattr(record, 'request_id'):
            log_data['request_id'] = record.request_id
        if hasattr(record, 'endpoint'):
            log_data['endpoint'] = record.endpoint
        if hasattr(record, 'ip_address'):
            log_data['ip_address'] = record.ip_address
        
        # Agregar excepción si existe
        if record.exc_info:
            log_data['exception'] = self.formatException(record.exc_info)
        
        # En desarrollo, formato más legible
        if Config.DEBUG:
            return json.dumps(log_data, indent=2, ensure_ascii=False)
        else:
            return json.dumps(log_data, ensure_ascii=False)

def setup_logger(name=__name__, log_level=None):
    """
    Configura y retorna un logger estructurado.
    
    Args:
        name: Nombre del logger (generalmente __name__)
        log_level: Nivel de log (DEBUG, INFO, WARNING, ERROR, CRITICAL)
    
    Returns:
        logging.Logger: Logger configurado
    """
    if log_level is None:
        log_level = getattr(logging, Config.LOG_LEVEL.upper(), logging.INFO)
    
    logger = logging.getLogger(name)
    
    # Evitar agregar handlers múltiples veces
    if logger.handlers:
        return logger
    
    logger.setLevel(log_level)
    
    # Handler para consola
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(log_level)
    console_formatter = StructuredFormatter()
    console_handler.setFormatter(console_formatter)
    logger.addHandler(console_handler)
    
    # Handler para archivo (opcional)
    if Config.LOG_FILE and Config.LOG_FILE != '':
        try:
            log_path = Path(Config.LOG_FILE)
            log_path.parent.mkdir(parents=True, exist_ok=True)
            
            file_handler = logging.FileHandler(log_path, encoding='utf-8')
            file_handler.setLevel(log_level)
            file_formatter = StructuredFormatter()
            file_handler.setFormatter(file_formatter)
            logger.addHandler(file_handler)
        except Exception as e:
            # Si falla crear archivo, solo usar consola
            logger.warning(f"No se pudo configurar archivo de log: {e}")
    
    return logger

# Logger principal de la aplicación
app_logger = setup_logger('roadfy')

def get_logger(name=__name__):
    """Obtiene un logger para un módulo específico."""
    return setup_logger(name)
