"""
Logging configuration
"""
import logging
import os
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, Any, Optional

from core.config import get_settings


settings = get_settings()

# Create logs directory if it doesn't exist
logs_dir = Path("logs")
logs_dir.mkdir(exist_ok=True)

# Log file path with timestamp
log_file = logs_dir / f"{datetime.now().strftime('%Y-%m-%d')}.log"


def configure_logging() -> None:
    """Configure logging for the application."""
    log_level = getattr(logging, settings.LOG_LEVEL.upper(), logging.INFO)
    
    # Configure root logger
    logging.basicConfig(
        level=log_level,
        format=settings.LOG_FORMAT,
        handlers=[
            logging.StreamHandler(sys.stdout),
            logging.FileHandler(log_file),
        ],
    )
    
    # Set log level for external libraries
    logging.getLogger("uvicorn").setLevel(logging.WARNING)
    logging.getLogger("sqlalchemy").setLevel(logging.WARNING)
    logging.getLogger("alembic").setLevel(logging.WARNING)
    
    # Log configuration
    logger = logging.getLogger(__name__)
    logger.debug(f"Logging configured with level: {settings.LOG_LEVEL}")
    logger.debug(f"Log file: {log_file}")


class RequestContextFilter(logging.Filter):
    """
    Filter that adds request context information to log records.
    """
    
    def __init__(self, request_id: Optional[str] = None, user_id: Optional[str] = None):
        """
        Initialize the filter.
        
        Args:
            request_id: Request ID
            user_id: User ID
        """
        super().__init__()
        self.request_id = request_id
        self.user_id = user_id
    
    def filter(self, record: logging.LogRecord) -> bool:
        """
        Add request context information to log records.
        
        Args:
            record: Log record
            
        Returns:
            True to include the record, False to exclude
        """
        record.request_id = getattr(self, "request_id", "")
        record.user_id = getattr(self, "user_id", "")
        return True


class RequestLogger:
    """
    Logger for request-specific logging.
    """
    
    def __init__(self, request_id: str, user_id: Optional[str] = None):
        """
        Initialize the logger.
        
        Args:
            request_id: Request ID
            user_id: User ID
        """
        self.request_id = request_id
        self.user_id = user_id
        self.logger = logging.getLogger("request")
        
        # Add filter for request context
        request_filter = RequestContextFilter(request_id, user_id)
        self.logger.addFilter(request_filter)
    
    def info(self, message: str, extra: Optional[Dict[str, Any]] = None) -> None:
        """
        Log an info message.
        
        Args:
            message: Log message
            extra: Extra information to include in the log record
        """
        self.logger.info(message, extra=extra or {})
    
    def error(self, message: str, extra: Optional[Dict[str, Any]] = None) -> None:
        """
        Log an error message.
        
        Args:
            message: Log message
            extra: Extra information to include in the log record
        """
        self.logger.error(message, extra=extra or {})
    
    def warning(self, message: str, extra: Optional[Dict[str, Any]] = None) -> None:
        """
        Log a warning message.
        
        Args:
            message: Log message
            extra: Extra information to include in the log record
        """
        self.logger.warning(message, extra=extra or {})
    
    def debug(self, message: str, extra: Optional[Dict[str, Any]] = None) -> None:
        """
        Log a debug message.
        
        Args:
            message: Log message
            extra: Extra information to include in the log record
        """
        self.logger.debug(message, extra=extra or {})


# Initialize logging
configure_logging()