import time
import math
import pydirectinput


class DeathManager:
    def __init__(self, patrol_system, resurrection_waypoints_path=None,
                 release_spirit_key='9', resurrect_key='0'):
        self.corpse_pos = None
        self.patrol_system = patrol_system
        self.is_running_to_corpse = False
        self._spirit_release_sent = False
        self.resurrection_waypoints = self._load_waypoints(resurrection_waypoints_path)
        self._resurrection_completed = False
        self.release_spirit_key = str(release_spirit_key).strip() or '9'
        self.resurrect_key = str(resurrect_key).strip() or '0'

    def _load_waypoints(self, path):
        """加载复活点路线 JSON，可置空。"""
        if not path:
            return None
        import json, os
        if not os.path.exists(path):
            return None
        try:
            with open(path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            if isinstance(data, list) and len(data) > 0:
                return [(float(p[0]), float(p[1])) for p in data]
        except Exception:
            pass
        return None

    def reset_when_alive(self):
        """存活时清标志，避免下次死亡无法再次释放灵魂/记录尸体坐标。"""
        self._spirit_release_sent = False
        self.corpse_pos = None
        self.is_running_to_corpse = False
        self._resurrection_completed = 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(self.release_spirit_key)
        time.sleep(5)  # 等待加载界面

    def run_to_corpse(self, state, get_state=None):
        """
        2. 跑尸寻路逻辑：坐标与朝向从 player_position 获取。

        两阶段逻辑：
        - 阶段1：若配置了复活点路线，先跑完该路线
        - 阶段2：路线跑完后（或无路线），跑向尸体
        """
        if not self.corpse_pos:
            return

        # 阶段1：复活路线未走完 → navigate_path 跑完路线
        if self.resurrection_waypoints and not self._resurrection_completed:
            if get_state is None:
                return
            if self.patrol_system.navigate_path(get_state, self.resurrection_waypoints):
                self._resurrection_completed = True
                print(">>> 复活路线跑完，开始跑向尸体...")
            return

        # 阶段2：复活路线走完（或无） → 直接跑向尸体
        is_arrived = self.patrol_system.navigate_to_point(state, self.corpse_pos)
        # 如果距离尸体很近（0.005 约等于 10-20 码）
        if is_arrived:
            print(">>> 已到达尸体附近，尝试复活...")
            pydirectinput.press(self.resurrect_key)
            time.sleep(5)
            self.is_running_to_corpse = False
            self.corpse_pos = None
            return

