import os
from logging.handlers import TimedRotatingFileHandler


class FFileHandler(TimedRotatingFileHandler):
    def __init__(self, conn_obj=None, **kwargs):
        log_dir = kwargs.get("log_dir", "./logs")
        filename = kwargs.get("filename", "app.log")
        rotation = kwargs.get("rotation", "daily")
        backup_count = kwargs.get("backup_count", 7)

        os.makedirs(log_dir, exist_ok=True)
        filepath = os.path.join(log_dir, filename)

        # Map rotation keyword → when
        when_map = {
            "daily": "D",
            "weekly": "W0",
            "monthly": "midnight",  # crude monthly fallback
        }
        when = when_map.get(rotation, "D")

        # Call super with the correct filename
        super().__init__(filepath, when=when, interval=1, backupCount=backup_count)
