import cv2

from mower.utils import config
from mower.utils import typealias as tp
from mower.utils.generate_image import generate_image
from mower.utils.image import cropimg, loadres
from mower.utils.log import logger


def find_text(
    text: str, size: int, threshold: float = 0.8, scope: tp.Scope | None = None
) -> tp.Scope | None:
    "模板匹配找文字"
    res = generate_image(text, size)
    h, w = res.shape
    if scope:
        x, y = scope[0]
        img = cropimg(config.recog.gray, scope)
    else:
        x, y = (0, 0)
        img = config.recog.gray
    result = cv2.matchTemplate(img, res, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    logger.debug(f'"{text}": {max_val}')
    if max_val < threshold:
        return None
    p1 = (max_loc[0] + x, max_loc[1] + y)
    p2 = (p1[0] + w, p1[1] + h)
    return p1, p2


def detect_layer() -> int:
    # 检测当前层数
    layer, val = 0, 0
    for i in range(1, 6):
        res = loadres(f"rogue/layer_{config.conf.maa_rg_theme}/{str(i)}", True)
        img = cropimg(config.recog.gray, ((880, 20), (1080, 70)))
        result = cv2.matchTemplate(img, res, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
        if max_val > val:
            layer = i
            val = max_val
    return layer


def get_idea_num() -> int:
    return config.recog.num.number_int(
        "secret_front", ((1265, 1025), (1350, 1070)), 32, 120
    )


def get_money_num() -> int:
    return config.recog.num.number_int("riic_base", ((1760, 30), (1880, 70)), 25, 130)
