from mower.solvers.fight.battle_choose.battle_fill_choose import BattleFillChooseSolver
from mower.solvers.infra.base_mixin import BaseMixin
from mower.solvers.infra.enter_room import EnterRoomSolver
from mower.utils import config
from mower.utils import typealias as tp
from mower.utils.character_recognize import match_portrait
from mower.utils.email import assistants_template, send_message
from mower.utils.graph import SceneGraphSolver
from mower.utils.log import logger
from mower.utils.recognize import Scene

pos_name = ["控制中枢", "B1", "B2", "B3", "B4"]

trust_number_scope = [
    ((590, 500), (670, 530)),
    ((230, 950), (310, 980)),
    ((470, 950), (550, 980)),
    ((710, 950), (790, 980)),
    ((950, 950), (1030, 980)),
]

portrait_scope = [
    ((542, 250), (729, 380)),
    ((183, 713), (370, 823)),
    ((423, 713), (610, 823)),
    ((663, 713), (850, 823)),
    ((903, 713), (1090, 823)),
]


class SwitchAssistantsSolver(SceneGraphSolver, BaseMixin):
    solver_name = "基建副手"

    def run(self) -> None:
        if not config.conf.switch_assistants:
            return True
        self.limit = config.conf.trust_limit  # 设置的信赖值阈值
        self.assistants_before = []  # 记录切换前的干员
        self.switched_scope = {}  # 记录已切换过的位置
        self.init = False
        self.switched = False
        result = super().run()
        assistants_after = self.current_operators if self.switched else []
        send_message(
            assistants_template.render(
                assistants_before=self.assistants_before,
                assistants_after=assistants_after,
                limit=str(self.limit) + "%",
            ),
            "基建副手汇总通知",
            "INFO",
            config.recog.img,
        )
        return result

    @property
    def current_operators(self) -> list:
        result = []
        opers = match_portrait(config.recog.gray, segment=portrait_scope)
        for i in range(5):
            if (num := self.number(trust_number_scope[i], 14, 130)) != -1:
                result.append([pos_name[i], opers[i][0], str(num) + "%"])
            else:
                result.append([pos_name[i], None])
        return result

    def number(self, scope: tp.Scope, height: int, thres: int) -> int:
        "数字识别"
        return config.recog.num.number_int(
            "noto", scope, height, thres, rect_ed=-3, res_if_error="-1"
        )

    def transition(self) -> bool:
        if (scene := self.scene()) == Scene.RIIC_REPORT:
            if self.animation():
                return
            if not self.find("riic/assistants_title"):
                self.ctap((20, 80), 3)
                return

            if not self.init:
                self.assistants_before = self.current_operators
                self.black_list = [
                    assistant[1] for assistant in self.assistants_before if assistant[1]
                ]  # 记录已在位置和选择过的干员
                self.init = True

            if pos := self.find("riic/none"):
                self.ctap(pos, 3)
                self.switched = True
                return
            for pos in trust_number_scope:
                if (num := self.number(pos, 14, 130)) >= self.limit:
                    if (
                        pos in self.switched_scope and self.switched_scope[pos]
                    ):  # 已经换过的位置，号里剩余干员信赖值低于阈值的不超过5
                        return True
                    logger.debug(f"{pos}, {num}")
                    self.ctap(pos, 3)
                    self.switched = True
                    self.switched_scope[pos] = False
                    self.switched_pos = pos
                    return
            return True
        elif scene == Scene.OPERATOR_AGENT_SELECT:
            if not self.switched_scope[self.switched_pos]:
                if name := BattleFillChooseSolver().run("信赖值", 1, self.black_list):
                    self.black_list.append(name[0])
                    self.switched_scope[self.switched_pos] = True

            if self.find("choose_agent/battle_confirm"):
                self.ctap("choose_agent/battle_confirm", 3)

        elif scene == Scene.CTRLCENTER_ASSISTANT:
            self.scene_graph_step(Scene.RIIC_REPORT)
        elif scene in self.waiting_scene:
            self.waiting_solver()
        else:
            EnterRoomSolver().run("central", False)
