import cv2
import numpy as np

class UIDetector:
    """
    Module phân tích giao diện game (UI): Thanh máu (HP), Mana (MP), Thanh máu quái (Target).
    Sử dụng Color Masking HSV để tính phần trăm cực nhanh (< 1ms).
    """
    def __init__(self, config: dict):
        self.config = config

    def calculate_bar_percentage(self, frame: np.ndarray, roi: list, lower_hsv: list, upper_hsv: list) -> float:
        """
        Cắt vùng ROI thanh máu/mana và đếm số lượng pixel trùng màu để tính % thanh.
        roi = [x1, y1, x2, y2]
        """
        x1, y1, x2, y2 = roi
        h, w = frame.shape[:2]

        # Kiểm tra biên hợp lệ
        if x2 > w or y2 > h or x1 >= x2 or y1 >= y2:
            return 0.0

        bar_crop = frame[y1:y2, x1:x2]
        hsv = cv2.cvtColor(bar_crop, cv2.COLOR_BGR2HSV)

        # Tạo mask lọc màu
        mask = cv2.inRange(hsv, np.array(lower_hsv), np.array(upper_hsv))

        # Tính tỷ lệ pixel màu trên toàn bộ diện tích thanh
        total_pixels = mask.size
        if total_pixels == 0:
            return 0.0
            
        colored_pixels = cv2.countNonZero(mask)
        return float(colored_pixels / total_pixels)

    def get_player_hp_percentage(self, frame: np.ndarray) -> float:
        hp_cfg = self.config["perception"]["hp_bar"]
        return self.calculate_bar_percentage(
            frame,
            hp_cfg["roi"],
            hp_cfg["color_hsv_lower"],
            hp_cfg["color_hsv_upper"]
        )

    def is_target_selected(self, frame: np.ndarray) -> bool:
        target_cfg = self.config["perception"]["target_bar"]
        ratio = self.calculate_bar_percentage(
            frame,
            target_cfg["roi"],
            target_cfg["color_hsv_lower"],
            target_cfg["color_hsv_upper"]
        )
        return ratio > 0.10  # Có thanh máu quái xuất hiện trên màn hình
