from datetime import datetime, timedelta

from mower.utils import config
from mower.utils.generate_image import generate_image
from mower.utils.graph import SceneGraphSolver
from mower.utils.image import cmatch, cropimg, loadres
from mower.utils.log import logger
from mower.utils.rapidocr import ocr_rec
from mower.utils.recognize import Scene
from mower.utils.vector import va

from .utils import is_full

xl = list(range(230, 1655, 473))
yl = [230, 573]
sl = []
for y in yl:
    for x in xl:
        tl = (x, y)
        sl.append((tl, va(tl, (10, 10))))

ec_pos = [
    ((270, 270), (600, 350)),
    ((950, 270), (1300, 350)),
    ((1650, 270), (1920, 350)),
]


class SSSNaviSolver(SceneGraphSolver):
    solver_name = "保全导航"

    def run(self) -> bool:
        copilot = config.works["sss"]
        self.start_time = datetime.now()
        self.success = False
        self.mode = config.conf.sss.mode  # "normal"：正常模式，"ex"：应急模式
        self.choose_agent = config.conf.sss.choose_agent
        self.type = generate_image(copilot.stage_name, 36)
        self.ec = copilot.buff
        self.device: list[str] = copilot.equipment

        super().run()
        return self.success

    def get_device(self) -> list[str]:
        A = loadres("sss/A")
        result = []
        for scope in sl:
            img = cropimg(config.recog.img, scope)
            result.append("A" if cmatch(A, img, 60) else "B")
        logger.debug(result)
        return result

    def transition(self):
        if datetime.now() - self.start_time > timedelta(minutes=2):
            logger.error("保全导航超时")
            return True
        elif (scene := self.scene()) in [Scene.SSS_DEPLOY, Scene.SSS_REDEPLOY]:
            delta = (datetime.now() - self.start_time).total_seconds()
            logger.info(f"保全导航成功，用时{delta:.0f}秒")
            self.success = True
            return True
        elif scene == Scene.SSS_MAIN:
            if config.conf.sss.finish_while_full and is_full():
                return True
            if self.find("sss/EC_up"):
                self.tap("sss/EC_up")
                return
            score, scope = config.recog.matcher.match(self.type)
            if score > 0.85:
                pos = self.get_pos(scope)
                self.tap(va(pos, (-240, 0)))
        elif scene == Scene.SSS_START:
            if self.mode == "normal" and self.find("sss/switch_to_normal"):
                self.tap("sss/switch_to_normal")
                return
            elif self.mode == "ex" and self.find("sss/switch_to_ex"):
                self.tap("sss/switch_to_ex")
                return
            if config.conf.sss.finish_while_full and self.find("sss/ope/prts"):
                return True

            self.tap((1555, 966))
        elif scene == Scene.SSS_CHOOSE_EC:
            for scope in ec_pos:
                img = cropimg(config.recog.img, scope)
                if ocr_rec(img) == self.ec:
                    self.tap(scope)
                    return

        elif scene == Scene.SSS_EC:
            self.tap("sss/ec")
        elif scene == Scene.SSS_DEVICE:
            current = self.get_device()
            for i in range(8):
                if current[i] != self.device[i]:
                    self.tap(sl[i])
                    return
            self.ctap((1644, 969))
        elif scene == Scene.SSS_SQUAD:
            if config.conf.sss.choose_agent:
                return True
            self.tap("sss/squad")
        elif scene == Scene.SSS_EC_EX:
            self.tap("sss/check_ex")

        else:
            self.scene_graph_step(Scene.SSS_MAIN)
