from datetime import datetime, timedelta

import cv2

from mower.models import Digtal
from mower.solvers.fight.battle_choose.battle_fill_choose import BattleFillChooseSolver
from mower.solvers.infra.base_mixin import BaseMixin
from mower.utils import config
from mower.utils import typealias as tp
from mower.utils.graph import SceneGraphSolver
from mower.utils.image import cropimg, thres2
from mower.utils.log import logger
from mower.utils.recognize import Scene

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


class SwitchAssistantsSolver(SceneGraphSolver, BaseMixin):
    def run(self) -> None:
        logger.info("Start:切换高信赖基建副手")
        self.start_time = datetime.now()
        self.limit = config.conf.trust_limit  # 设置的信赖值阈值
        self.black_list = []  # 记录选择过的干员
        super().run()

    def timeout(self) -> bool:
        return datetime.now() > self.start_time + timedelta(seconds=180)

    def number(self, scope: tp.Scope, height: int, thres: int) -> int:
        "数字识别"
        img = cropimg(config.recog.gray, scope)
        default_height = 25
        if height != default_height:
            scale = 25 / height
            img = cv2.resize(img, None, None, scale, scale)
        img = thres2(img, thres)
        contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        rect = [cv2.boundingRect(c) for c in contours]
        rect.sort(key=lambda c: c[0])
        rect = rect[:-3]

        value = 0

        for x, y, w, h in rect:
            digit = cropimg(img, ((x, y), (x + w, y + h)))
            digit = cv2.copyMakeBorder(
                digit, 10, 10, 10, 10, cv2.BORDER_CONSTANT, None, (0,)
            )
            score = []
            for i in range(10):
                im = Digtal().riic_base_digits[i]
                result = cv2.matchTemplate(digit, im, cv2.TM_SQDIFF_NORMED)
                min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
                score.append(min_val)
            value = value * 10 + score.index(min(score))

        return value

    def transition(self) -> bool:
        if self.timeout():
            logger.error("切换高信赖基建副手超时,请检查干员和设置的阈值")
            return True
        if (scene := self.scene()) == Scene.RIIC_REPORT:
            if not self.find("riic/assistants_title"):
                self.tap((20, 80))
                return
            if pos := self.find("riic/none"):
                self.tap(pos)
                return
            for pos in trust_number_scope:
                if (num := self.number(pos, 14, 130)) > self.limit:
                    logger.debug(f"{pos}, {num}")
                    self.tap(pos)
                    return
            return True
        elif scene == Scene.OPERATOR_AGENT_SELECT:
            if name := BattleFillChooseSolver().run("信赖值", 1, self.black_list):
                self.black_list.append(name[0])
                if self.find("choose_agent/battle_confirm"):
                    self.tap_element("choose_agent/battle_confirm")
        else:
            self.scene_graph_step(Scene.RIIC_REPORT)
