from datetime import datetime
from typing import Literal

import cv2

from mower.utils import config
from mower.utils.graph import SceneGraphSolver
from mower.utils.log import logger
from mower.utils.scene import Scene
from mower.utils.vector import va, vs

from .utils import generate_name


class classproperty:
    def __init__(self, method=None):
        self.fget = method

    def __get__(self, instance, cls=None):
        return self.fget(cls)

    def getter(self, method):
        self.fget = method
        return self


class ActivityNavigation(SceneGraphSolver):
    solver_name = "活动关卡导航"

    _location = {
        "EP-1": (0, 0),
        "EP-2": [302, -196],
        "EP-3": [483, -383],
        "EP-4": [791, -224],
        "EP-5": [1101, -338],
        "EP-6": [1385, -453],
        "EP-7": [2001, -116],
        "EP-8": [2279, -391],
    }

    @classproperty
    def location(cls):
        if datetime.now() > datetime(2024, 12, 19, 4):
            return {}
        return cls._location

    def generate_names(self):
        names = {}
        for name in self._location.keys():
            names[name] = generate_name(name, pad_right=10)
        self.names = names

    def run(self, name: str, mode: Literal["auto", "copy"] = "auto") -> None:
        logger.info("导航至活动关卡")
        self.switch_to_ex = False
        if name.endswith("#"):
            name = name[:-1]
            self.switch_to_ex = True
        self.name = name
        self.mode = mode
        self.generate_names()
        super().run()
        return True

    def transition(self) -> bool:
        if (scene := self.scene()) == Scene.TERMINAL_MAIN:
            self.terminal_entry("navigation/activity/terminal.jpg")
        elif scene == Scene.ACTIVITY_MAIN:
            self.tap("navigation/activity/entry")
        elif scene == Scene.ACTIVITY_CHOOSE_LEVEL:
            if (
                self.mode == "copy"
                and (result := config.recog.match("story_stage"))
                and result[0] > 0.8
            ):
                self.tap(result[1])
                return

            name, val, loc = None, 1, None
            for n, img in self.names.items():
                result = cv2.matchTemplate(config.recog.gray, img, cv2.TM_SQDIFF_NORMED)
                min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
                if min_val < val:
                    val = min_val
                    loc = min_loc
                    name = n
            logger.debug(f"在{loc}找到关卡{name}")

            target = va(vs(loc, self.location[name]), self.location[self.name])
            if target[0] + 200 > 1920:
                self.swipe_noinertia((1400, 540), (-1000, 0))
            elif target[0] < 0:
                self.swipe_noinertia((400, 540), (1000, 0))
            else:
                self.tap(va(target, (60, 20)))
        elif scene == Scene.OPERATOR_BEFORE:
            if self.find("ope_ex_mode") and self.switch_to_ex:
                self.tap("ope_ex_mode")
                return

            if self.mode == "auto":
                return True
            elif self.mode == "copy":
                if not self.switch_to_ex:
                    if config.recog.gray[65][1333] < 200:
                        self.sleep()
                        return
                    # 取消代理作战
                    if config.recog.gray[907][1600] > 127 and not self.find(
                        "ope_agency_lock"
                    ):
                        self.tap((1776, 908))
                        return
                    self.tap("ope_start")
                else:
                    self.tap("ope_ex_start")
        elif scene == Scene.OPERATOR_SELECT and self.mode == "copy":
            return True
        elif scene in [Scene.OPERATOR_RECOVER_ORIGINITE, Scene.OPERATOR_RECOVER_POTION]:
            return True
        elif scene == Scene.STORY_STAGE:
            self.tap("start_story")

        else:
            self.scene_graph_step(Scene.TERMINAL_MAIN)
