# coding:utf-8
from service.frontlinkcheck import checkByPortLink, checkByHostLink
from cbb.frame.context import contextUtil
from cbb.frame.base import baseUtil
from checkitems.evaluate_pre_check import link_pre_check
from cbb.frame.ruleConfig import common
from java.lang import Exception as JException
from com.huawei.ism.tool.obase.exception import ToolException

ITEM_ID = "rest_frontLinkCheck"


def execute(context):
    logger = common.getLogger(contextUtil.getLogger(context), __file__)
    # 执行升级前检查

    try:
        flag, err_msg, cli_ret = link_pre_check(context)
        if flag:
            return flag, err_msg, cli_ret

        devVersion = contextUtil.getCurVersion(context)
        devType = contextUtil.getDevType(context)

        if baseUtil.isDoradoDev(devType):
            logger.logInfo("run checkByPortLink")
            return checkByPortLink.execute(context)

        # V1R1C30/V2R2C30/V3R1C20之前的版本走主机链路检查方案
        if (
            ("V1" in devVersion and devVersion < "V100R001C30")
            or ("V2" in devVersion and devVersion < "V200R002C30")
            or (
                "V3" in devVersion
                and (devVersion < "V300R001C20" or "V300R002C10" in devVersion)
            )
        ):
            logger.logInfo("run checkByHostLink")
            return checkByHostLink.execute(context)

        # V5R7C20及之后的版本走主机链路的方案
        if ("V3" in devVersion and devVersion >= "V300R006C30") or (
            "V5" in devVersion and devVersion >= "V500R007C20"
        ):
            logger.logInfo("run checkByPortLink")
            return checkByPortLink.execute(context)

        # V5R7C20之前的版本走端口反查的方案
        logger.logInfo("run checkByPortLink")
        return checkByPortLink.execute(context)
    except (Exception, JException, ToolException) as e:
        logger.logError(e)
        error_id = "login.clis.overrun.info" if "PwdCLIOverrunException" in str(e) else "query.result.abnormal"
        return (
            False,
            common.getMsg(context.get("lang"), error_id),
            "",
        )
