import os
import socket

from loguru import logger

from algo_backend.config import LoguruConfig as LogConfig

from ..common import BasicLogStarter
from .log_clean import LoguruCleaner
from .log_setup import LoguruSetup


class LoguruStarter(BasicLogStarter):
    """
    容器内日志目录默认是：/logger/服务名
    """

    def __init__(self, service_name: str):
        super().__init__(service_name)

    @property
    def service_log_dir(self):
        return os.path.join(LogConfig.LOGGER_PATH, self.service_name)

    def setup_log(self):
        """
        日志设置
        """

        LoguruSetup.rotate_daily(
            log_dir=self.service_log_dir,
            service_name=self.add_container_id(service_name=self.service_name),
            add_pid_suffix=True,
            save_info=LogConfig.SAVE_INFO_LEVEL,
            save_debug=LogConfig.SAVE_DEBUG_LOG,
        )

        for pkg in LogConfig.get_disable_log_pkg():
            # 忽略一些包的日志
            logger.debug(f"ignore log: {pkg}")
            logger.disable(pkg)

    def run_log_cleaner(self):
        """
        启动定时任务清理日志
        """
        LoguruCleaner.schedule_run(
            log_dir=self.service_log_dir,
            retention_day=LogConfig.LOG_RETENTION_DAY,
        )

    @classmethod
    def add_container_id(cls, service_name: str):
        if not LogConfig.LOG_ADD_CONTAINED_ID:
            logger.info("日志名不增加containerId")
            return service_name

        try:
            socket_hostname = f"-{socket.gethostname()}"
        except:
            socket_hostname = ""
        if service_name in socket_hostname:
            return service_name
        else:
            return f"{service_name}{socket_hostname}"
