from copy import deepcopy

from mower.data import agent_list
from mower.solvers.fight.battle_choose.battle_filter import BattleFilterSolver
from mower.solvers.fight.battle_choose.battle_tag_choose import BattleTagChoose
from mower.solvers.fight.battle_choose.choose_skill import ChooseSkillSolver
from mower.solvers.navigation import NavigationSolver
from mower.utils import config
from mower.utils.character_recognize import (
    operator_team_select,
)
from mower.utils.graph.utils import SceneGraphSolver
from mower.utils.image import cropimg
from mower.utils.log import logger
from mower.utils.scene import Scene


class BattleAgentChooseSolver(SceneGraphSolver):
    def run(self, agents: list, level_name: str = "") -> None:
        if agents == []:
            raise ValueError("干员列表为空")
        self.agents = agents
        self.agents_copy = deepcopy(agents)
        self.cleard = False
        self.filter = False
        self.agent = None
        self.choosed = []
        self.final_check = False
        self.check = []
        self.lack = []
        self.tmp_data = None
        self.tag = "ALL"
        self.level_name = level_name
        super().run()

        return self.lack

    def choose_agents(self):
        if pos := self.find("choose_agent/open_profession"):
            self.tap(pos, interval=0.1)

        if self.agent is None:
            if len(self.agents_copy) > 0:
                self.agent = self.agents_copy.pop(0)

                if "opers" in self.agent:
                    tag = agent_list[self.agent["opers"][-1]["name"]]["profession"]
                else:
                    if self.agent["name"] == "阿米娅":
                        tag = "ALL"
                    else:
                        tag = agent_list[self.agent["name"]]["profession"]

                BattleTagChoose().run(tag)
            else:
                return True
        agents = dict(operator_team_select(config.recog.img))

        if "opers" in self.agent:
            for i in self.agent["opers"]:
                if i["name"] in agents.keys():
                    self.agent = i
                    logger.debug(f"干员组选择：{self.agent}")
                    return
        else:
            agent_name = self.agent["name"]
            if agent_name in agents.keys():
                if agents[agent_name][0][0] > 1650:
                    self.swipe_noinertia((1000, 540), (-500, 0))
                    return
                if self.is_choosed(agents[agent_name]):
                    logger.debug(f"干员选好：{self.agent}")
                    ChooseSkillSolver().run(self.agent["skill"])
                    self.choosed.append(agent_name)
                    self.agent = None
                    return
                logger.info(f"干员选择：{self.agent}")
                self.ctap(agents[agent_name], 1, config.screenshot_avg / 1000)
                return
        if list(agents.keys())[-1] == self.tmp_data or list(agents.keys())[-1] is None:
            logger.error(f"选择干员: {self.agent}失败 滑动次数过多")
            self.lack.append(self.agent)
            self.agent = None
            return

        self.swipe_noinertia((1000, 540), (-1900, 0))

        self.tmp_data = list(agents.keys())[-1]

    def is_choosed(self, scope) -> bool:
        if (
            cropimg(
                config.recog.img,
                [
                    [scope[0][0] + 0, scope[0][1] - 86],
                    [scope[0][0] + 1, scope[0][1] - 85],
                ],
            )[0][0][0]
            < 50
        ):
            return True
        return False

    def transition(self) -> bool:
        if (scene := self.scene()) == Scene.OPERATOR_AGENT_SELECT:
            if self.filter is False:
                BattleTagChoose().run("ALL")
                BattleFilterSolver().run("等级", ascending=False)
                self.filter = True
            if self.cleard is False:
                if self.find("choose_agent/battle_empty"):
                    self.cleard = True
                else:
                    self.tap_element("choose_agent/clear_battle", interval=0.1)
                return
            return self.choose_agents()
        elif scene == Scene.OPERATOR_SELECT:
            self.tap_element("choose_agent/fast_select")
        elif scene == Scene.SSS_SQUAD:
            self.tap_element("sss/choose/fast_select")
        elif scene in self.waiting_scene:
            self.waiting_solver()
        else:
            NavigationSolver().run(self.level_name, mode="copy")
