import uvicorn
from huibiao_framework.backend.metrics import PrometheusContext

from huibiao_framework.backend.log_utils import ServiceLoggerManager
from huibiao_framework.config import ServiceConfig


class HuibiaoServiceStarter:
    def __init__(self, service_name: str):
        self.service_name = service_name

    def setup_multi_process_metrics(self):
        # 初始化prometheus多进程的设置
        PrometheusContext.init()
        return self

    def setup_par_pid_log(self):
        # 多worker时，主进程的日志设置
        ServiceLoggerManager.setup_log(self.service_name)
        return self

    def setup_log_cleaner(self):
        # 启动定时任务清理日志
        ServiceLoggerManager.run_log_cleaner(self.service_name)
        return self

    def main_pid_setup(self):
        """
        主进程中的设置
        """
        self.setup_multi_process_metrics()
        self.setup_par_pid_log()
        self.setup_log_cleaner()
        return self

    @classmethod
    def run(
        cls,
        app_str: str = "app.backend.application:app",
        host: str = "0.0.0.0",
        **kwargs,
    ):
        # 启动服务
        uvicorn.run(
            app_str,
            host=host,
            port=ServiceConfig.HTTP_PORT,
            timeout_keep_alive=ServiceConfig.TIMEOUT_KEEP_ALIVE,
            workers=ServiceConfig.PROCESS_NUM,
            **kwargs,
        )
