import cv2

from mower.solvers.infra.enter_room import EnterRoomSolver
from mower.utils import config, rapidocr
from mower.utils.graph import SceneGraphSolver
from mower.utils.image import cropimg
from mower.utils.log import logger
from mower.utils.recognize import Scene

from .utils import clue_cls, exit_pos


class ReceiveSolver(SceneGraphSolver):
    def run(self) -> None:
        super().run()

    def transition(self) -> bool:
        if (scene := self.scene()) == Scene.INFRA_DETAILS:
            self.tap((725, 850))
        elif scene == Scene.INFRA_CONFIDENTIAL:
            receive_scope = ((1815, 360), (1895, 410))
            if self.find("clue/badge_new", scope=receive_scope):
                self.ctap((1800, 430))
            else:
                return True
        elif scene == Scene.CLUE_RECEIVE:
            if self.find("infra_complete\信用", scope=((1440, 130), (1920, 193))):
                self.sleep()
                return
            if clue := clue_cls("receive"):
                name_scope = ((1580, 220), (1880, 255))
                name_img = cropimg(config.recog.gray, name_scope)
                name_img = cv2.copyMakeBorder(
                    name_img, 48, 48, 48, 48, cv2.BORDER_REPLICATE
                )
                name = rapidocr.engine(
                    name_img,
                    use_det=True,
                    use_cls=False,
                    use_rec=True,
                )[0][0][1]
                name = name.strip() if name else "好友"
                logger.info(f"接收{name}的{clue}号线索")
                self.tap(name_scope)
            else:
                self.tap(exit_pos)
        elif scene in self.waiting_scene:
            self.waiting_solver()
        else:
            EnterRoomSolver().run("meeting", detail=False)
