import time
from enum import Enum, auto

class BotState(Enum):
    IDLE = auto()
    SEARCH_TARGET = auto()
    COMBAT = auto()
    LOOT = auto()
    EMERGENCY_HEAL = auto()

class GameStateMachine:
    """
    Máy trạng thái hữu hạn (FSM) quản lý logic vòng lặp điều khiển bot AION 2.
    """
    def __init__(self, config: dict, detector, actuator):
        self.config = config
        self.detector = detector
        self.actuator = actuator
        self.state = BotState.SEARCH_TARGET
        self.last_target_time = 0
        self.combat_skill_index = 0
        self.skills = self.config["actuator"]["keys"]["skills"]

    def update(self, frame):
        """
        Cập nhật trạng thái và thực hiện hành vi tương ứng theo từng khung hình.
        """
        # 1. Kiểm tra ưu tiên cao nhất: Cứu sinh (HP < threshold)
        hp_ratio = self.detector.get_player_hp_percentage(frame)
        low_hp_limit = self.config["perception"]["hp_bar"]["low_hp_threshold"]
        
        if hp_ratio < low_hp_limit and hp_ratio > 0.05:
            self.actuator.use_hp_potion()

        # 2. Xử lý trạng thái hoạt động chính
        if self.state == BotState.SEARCH_TARGET:
            if self.detector.is_target_selected(frame):
                print("[FSM] Đã khóa mục tiêu! Chuyển sang COMBAT.")
                self.state = BotState.COMBAT
            else:
                if time.time() - self.last_target_time > 1.0:
                    self.actuator.select_target()
                    self.last_target_time = time.time()

        elif self.state == BotState.COMBAT:
            if not self.detector.is_target_selected(frame):
                print("[FSM] Quái đã chết hoặc mất mục tiêu! Chuyển sang LOOT.")
                self.state = BotState.LOOT
                self.loot_start_time = time.time()
            else:
                # Xả chuỗi combo skill theo thứ tự
                skill_to_cast = self.skills[self.combat_skill_index % len(self.skills)]
                self.actuator.cast_combat_skill(skill_to_cast)
                self.combat_skill_index += 1
                time.time()

        elif self.state == BotState.LOOT:
            # Nhặt đồ trong 2 giây rồi tìm quái mới
            self.actuator.loot()
            if time.time() - self.loot_start_time > 2.0:
                print("[FSM] Nhặt đồ xong! Quay lại SEARCH_TARGET.")
                self.state = BotState.SEARCH_TARGET
