from .auto_fight import AutoFight
from .battle_choose import BattleChooseSolver


class FightSolver:
    def run(
        self,
        level_name: str,
        opers: list,
        actions: list,
        groups=[],
        auto_choose: bool = True,
        support_oper: str = "",
        retry_times: int = 5,
    ):
        """
        Args:
            level_name: 关卡名
            opers: 干员列表
            actions: 行动列表
            groups: 干员组列表
            auto_choose: 是否自动选择干员编队
            support_oper: 助战干员
            retry_times: 战斗失败重试次数
        """
        self.check_opers_skill(opers, groups)
        if support_oper:
            support_oper = self.find_support_oper(support_oper, opers, groups)
        if auto_choose:
            if not BattleChooseSolver().run(
                level_name,
                opers,
                groups,
                support_oper,
            ):
                return False
        while retry_times + 1:
            if AutoFight().run(level_name, opers, actions, groups):
                return True
            retry_times -= 1
        return False

    def check_opers_skill(self, opers: list, groups: list):
        for oper in opers:
            if "skill" not in oper:
                oper["skill"] = 1
            if "skill_usage" not in oper:
                oper["skill_usage"] = 0
        for group in groups:
            for oper in group["opers"]:
                if "skill" not in oper:
                    oper["skill"] = 1
                if "skill_usage" not in oper:
                    oper["skill_usage"] = 0

    def find_support_oper(self, support_oper: str, opers: list, groups: list):
        for op in opers + groups:
            if op["name"] == support_oper:
                op["support"] = True
                return [op]
