import time
import math
import pydirectinput


class DeathManager:
    def __init__(self, patrol_system):
        self.corpse_pos = None
        self.patrol_system = patrol_system
        self.is_running_to_corpse = False
        self._spirit_release_sent = False

    def reset_when_alive(self):
        """存活时清标志，避免下次死亡无法再次释放灵魂/记录尸体坐标。"""
        self._spirit_release_sent = False
        self.corpse_pos = None
        self.is_running_to_corpse = False

    def on_death(self, state):
        """1. 死亡瞬间调用：从 player_position 获取坐标并记录"""
        if self._spirit_release_sent:
            return
        self._spirit_release_sent = True
        self.corpse_pos = (state['x'], state['y'])
        self.is_running_to_corpse = True
        print(f">>> [系统] 记录死亡坐标: {self.corpse_pos}，准备释放灵魂...")
        pydirectinput.press('9')  # 绑定宏: /run RepopMe()
        time.sleep(5)  # 等待加载界面

    def run_to_corpse(self, state):
        """2. 跑尸寻路逻辑：坐标与朝向从 player_position 获取"""
        if not self.corpse_pos:
            return  
        
        is_arrived = self.patrol_system.navigate_to_point(state, self.corpse_pos)
        # 如果距离尸体很近（0.005 约等于 10-20 码）
        if is_arrived:
            print(">>> 已到达尸体附近，尝试复活...")
            pydirectinput.press('0') # 绑定宏: /run RetrieveCorpse()
            time.sleep(5)
            self.is_running_to_corpse = False
            self.corpse_pos = None
            return

    def handle_resurrection_popup(self):
        """处理复活确认框"""
        # 配合 Lua 插件自动点击，或者 Python 模拟按键
        pydirectinput.press('enter')