import logging
import sys
import os
from logging.handlers import RotatingFileHandler
from ..config import settings

def setup_logging():
    log_file = os.path.join(settings.LOG_DIR, "company_explorer_debug.log")
    
    # Create Formatter
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )
    
    # File Handler
    try:
        file_handler = RotatingFileHandler(log_file, maxBytes=10*1024*1024, backupCount=5)
        file_handler.setFormatter(formatter)
        file_handler.setLevel(logging.DEBUG)
    except Exception as e:
        print(f"FATAL: Could not create log file at {log_file}: {e}")
        return
    
    # Console Handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(formatter)
    console_handler.setLevel(logging.INFO) # Keep console clean
    
    # Root Logger Config
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG) # Catch ALL
    root_logger.addHandler(file_handler)
    root_logger.addHandler(console_handler)
    
    # Silence noisy libs partially
    logging.getLogger("uvicorn.access").setLevel(logging.INFO)
    logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO) # Set to DEBUG to see SQL queries!
    
    logging.info(f"Logging initialized. Writing to {log_file}")