#! /usr/bin/env python3
import os, sys
from pathlib import Path
import core.plugin as plugin
from core.release_flow import ReleaseFlow
import thirdparty.py_trees as py_trees
import core.logger as logger
from database import *
log = logger.get_logger()

def load_config():
    config_path = Path(__file__).parent.joinpath("configs", "customer.yaml")
    if not config_path.exists():
        config_path = config_path.parent.joinpath('customer_test.yaml')
    if not config_path.exists():
        log.error(f"customer config not found! {config_path}")
        sys.exit(-1)
    load_from_file(config_path)
    #
    check_config()
    

def check_config():
    """检查各种配置是否ok
    1. 比如参数是否合法
    2. 比如路径是否存在
    3. 比如配置是否存在
    """
    ReleaseOptions.check()
    BlackListDefault.check()
    BlackListInternal.check()
    ProductIngoreList.check()
    ChipIngoreList.check()
    DirAlias.check()

def set_log_level(level:str):
    """设置日志级别
    Args:
        level (str): 日志级别
    """
    map  = {
        'debug' : py_trees.logging.Level.DEBUG,
        'info'  : py_trees.logging.Level.INFO,
        'warn'  : py_trees.logging.Level.WARN,
        'error' : py_trees.logging.Level.ERROR,
    }
    py_trees.logging.level = map.get(level, py_trees.logging.Level.INFO)
    log.set_level(level)

def main():
    args = sys.argv[1:]
    ReleaseOptions.parse(args)
    set_log_level(ReleaseOptions.log)
    load_config()
    # py_trees.logging.level = py_trees.logging.Level.DEBUG
    plugins = plugin.PluginManager()
    release_flow = ReleaseFlow()
    release_flow.construct(plugins)
    release_flow.run()
    release_flow.shutdown()

if __name__ == '__main__':
    main()