from datetime import datetime, timedelta

import cv2
from scipy.signal import argrelmin
from skimage.metrics import structural_similarity

from mower.solvers.navigation import NavigationSolver
from mower.utils import config
from mower.utils.email import send_message
from mower.utils.graph import SceneGraphSolver
from mower.utils.image import cmatch, cropimg, loadres
from mower.utils.log import logger
from mower.utils.recognize import Scene

from .auto_fight import AutoFight
from .battle_choose import BattleChooseSolver


class CreditFight(SceneGraphSolver):
    solver_name = "信用作战"

    def run(self):
        if not config.conf.maa_credit_fight:
            return True
        if self.scheduler_stop_time:
            if datetime.now() + timedelta(minutes=3) >= self.scheduler_stop_time:
                logger.info("信用作战时间不够，主动退出")
                return False
        conf = config.conf.credit_fight
        self.opers = [{"name": conf.operator, "skill": conf.skill, "skill_usage": 1}]
        self.squad = conf.squad
        self.actions = [
            {"type": "SpeedUp"},
            {
                "type": "Deploy",
                "name": conf.operator,
                "location": [
                    conf.x,
                    conf.y,
                ],
                "direction": conf.direction,
            },
            {"type": "SkillDaemon"},
        ]
        self.check = False
        super().run()
        return True

    def choose_support(self):
        img = cropimg(config.recog.gray, ((0, 908), (1839, 983)))
        res = loadres("fight/choose", True)
        result = cv2.matchTemplate(img, res, cv2.TM_SQDIFF_NORMED)[0]
        threshold = 0.1
        match = []
        for i in argrelmin(result, order=100)[0]:
            if result[i] < threshold:
                match.append(i)
        logger.debug(match)
        x = match[0]
        return (x, 908), (x + 194, 983)

    def check_support_choosed(self):
        res = loadres("choose_agent/no_oper")
        if cmatch(cropimg(config.recog.img, ((1582, 235), (1722, 310))), res):
            gray = cropimg(config.recog.gray, ((1582, 235), (1722, 310)))
            res_gray = cv2.cvtColor(res, cv2.COLOR_RGB2GRAY)
            ssim = structural_similarity(gray, res_gray)
            logger.debug(f"cmatch+SSIM:{ssim=}")
            if ssim >= 0.9:
                return False
        return True

    def transition(self):
        if (scene := self.scene()) == Scene.OPERATOR_SELECT:
            if self.animation():
                return
            if self.check_support_choosed():
                # 开始行动
                AutoFight().run("OF-1", self.opers, self.actions, [])
            elif self.check:
                self.ctap((1660, 315), 3)
                return
            elif not BattleChooseSolver().run(self.opers, squad=self.squad):
                msg = "OF-1选人出现错误，请检查相关编队精英化等级与助战设置，*今天*不会继续进行信用作战"
                logger.info(msg)
                send_message(msg, level="ERROR")
                return True
            self.check = True

        elif scene == Scene.OPERATOR_SUPPORT:
            if self.animation():
                return
            self.ctap(self.choose_support(), 3)
        elif scene == Scene.OPERATOR_SUPPORT_AGENT:
            if self.animation():
                return
            self.ctap("fight/use", 3)
        elif scene == Scene.OPERATOR_FINISH:
            return True
        elif scene == Scene.OPERATOR_FAILED:
            msg = "OF-1失败，请检查干员，*今天*不会继续进行信用作战"
            logger.info(msg)
            send_message(msg, level="ERROR")
            return True
        elif scene in self.waiting_scene:
            self.waiting_solver()
        else:
            NavigationSolver().run("OF-1", "copy")
