from datetime import datetime, timedelta

from mower.utils import config
from mower.utils.graph import SceneGraphSolver
from mower.utils.log import logger
from mower.utils.recognize import Scene
from mower.utils.vector import va

from .utils.utils import find_text


class RogueNaviSolver(SceneGraphSolver):
    solver_name = "肉鸽导航"
    _title = {
        "Phantom": "古堡笔记",
        "Mizuki": "生态谱系",
        "Sami": "科考记录",
        "Sarkaz": "假说辑录",
    }

    def run(self) -> bool:
        self.start_time = datetime.now()
        self.success = False
        super().run()
        return self.success

    def transition(self):
        if datetime.now() - self.start_time > timedelta(minutes=2):
            logger.error("肉鸽导航超时")
            return True
        elif (scene := self.scene()) == Scene.TERMINAL_LONGTERM:
            self.ctap((770, 750), 3)
        elif scene == Scene.ROGUE_THEME_SELECT:
            if self.animation(((0, 600), (1920, 1080)), interval=0.1, ratio=0.15):
                return
            if pos := find_text(
                self._title[config.conf.maa_rg_theme], 25, scope=((0, 600), (1920, 660))
            ):
                self.ctap(va(pos[0], (320, 360)), 3)
            else:
                self.swipe_noinertia((400, 800), (1000, 0))

        elif scene == Scene.ROGUE_INDEX:
            delta = (datetime.now() - self.start_time).total_seconds()
            logger.info(f"肉鸽导航成功，用时{delta:.0f}秒")
            self.success = True
            return True
        else:
            self.scene_graph_step(Scene.TERMINAL_LONGTERM)
