import logging
import os
from logging.handlers import TimedRotatingFileHandler
from app.core.config import settings

def setup_logging():
    log_dir = "/app/logs"
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    log_file = os.path.join(log_dir, "backend.log")
    
    # Format
    log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    formatter = logging.Formatter(log_format)

    # Root Logger
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)

    # Clear existing handlers to avoid duplicates during reload
    if root_logger.handlers:
        root_logger.handlers = []

    # Console Handler
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    root_logger.addHandler(console_handler)

    # File Handler (Daily Rotation)
    file_handler = TimedRotatingFileHandler(
        log_file,
        when="midnight",
        interval=1,
        backupCount=30, # Keep 30 days
        encoding="utf-8"
    )
    file_handler.setFormatter(formatter)
    file_handler.suffix = "%Y-%m-%d" # Suffix for rotated files: backend.log.2023-10-10
    root_logger.addHandler(file_handler)

    # Update Uvicorn loggers to use our format and handlers
    # We want uvicorn internal logs to also go to our file
    uvicorn_logger_names = ["uvicorn", "uvicorn.access", "uvicorn.error"]
    for name in uvicorn_logger_names:
        u_logger = logging.getLogger(name)
        u_logger.handlers = [] # Remove default handlers
        u_logger.propagate = True # Let it propagate to root logger which has our file handler
        
    # Set explicit level for some verbose libraries if needed
    logging.getLogger("multipart").setLevel(logging.WARNING)
    
    # Return main logger
    return logging.getLogger("app")

