from __future__ import annotations

import logging
import os
from logging.handlers import RotatingFileHandler

from app.core.config import settings


def setup_logging() -> None:
    logger = logging.getLogger()
    if getattr(logger, "_connecthub_configured", False):
        return

    logger.setLevel(logging.INFO)
    formatter = logging.Formatter(
        fmt="%(asctime)s %(levelname)s %(name)s %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )

    sh = logging.StreamHandler()
    sh.setFormatter(formatter)
    logger.addHandler(sh)

    if settings.log_dir:
        os.makedirs(settings.log_dir, exist_ok=True)
        fh = RotatingFileHandler(
            os.path.join(settings.log_dir, "connecthub.log"),
            maxBytes=10 * 1024 * 1024,
            backupCount=5,
        )
        fh.setFormatter(formatter)
        logger.addHandler(fh)

    setattr(logger, "_connecthub_configured", True)


