import logging

from logging.handlers import RotatingFileHandler
from typing import Optional

from saas.tools.devops.fban.config import FBanConfig, ServiceSettings


def _get_log_file_path(config: FBanConfig, service_settings: Optional[ServiceSettings] = None) -> str:
    if service_settings is not None:
        return f'{config.log_file.parent}/{service_settings.service}.{service_settings.ctype}-{config.log_file.name}'

    return config.log_file.absolute()


def setup_logging(config: FBanConfig, service_settings: Optional[ServiceSettings] = None) -> None:
    if config.log_verbosity < 1:
        log_level = logging.WARNING
    elif config.log_verbosity < 2:
        log_level = logging.INFO
    else:
        log_level = logging.DEBUG

    logging.basicConfig(
        handlers=[
            RotatingFileHandler(
                _get_log_file_path(config, service_settings),
                maxBytes=config.logrotate_max_bytes,
                backupCount=config.logrotate_backup_count
            )
        ] if config.log_file else None,
        format='%(asctime)s | %(levelname)-7s | %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S',
        level=log_level,
        force=True
    )
