# core/logger.py

import logging
import os
from logging.handlers import RotatingFileHandler


LOG_BASE = "logs/actions"


def get_action_logger(action: str, session: str):

    """
    Central dynamic logger

    action  → module / system name
    session → phone / account / global
    """

    path = os.path.join(LOG_BASE, action)
    os.makedirs(path, exist_ok=True)

    logger_name = f"{action}_{session}"

    logger = logging.getLogger(logger_name)

    # جلوگیری از duplicate handler
    if logger.handlers:
        return logger

    logger.setLevel(logging.INFO)
    logger.propagate = False

    fmt = logging.Formatter(
        "%(asctime)s | %(levelname)s | %(name)s | %(message)s"
    )

    # ---------- FILE (Rotating) ----------
    file_handler = RotatingFileHandler(
        os.path.join(path, f"{session}.log"),
        maxBytes=5 * 1024 * 1024,   # 5MB
        backupCount=3,
        encoding="utf-8"
    )
    file_handler.setFormatter(fmt)

    # ---------- CONSOLE ----------
    console = logging.StreamHandler()
    console.setFormatter(fmt)

    logger.addHandler(file_handler)
    logger.addHandler(console)

    return logger
