import time
import json
import math
import ctypes
import win32gui
import win32api
import pynput
from pynput import keyboard

# 开启 DPI 意识，解决 Windows 缩放导致的坐标偏差
try:
    ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
    ctypes.windll.user32.SetProcessDPIAware()

# 配置
WIN_TITLE = "魔兽世界"
SAVE_FILE = "loot_path.json"

class PathRecorder:
    def __init__(self):
        self.is_recording = False
        self.points = []
        self.center_x = 0
        self.center_y = 0
        
    def get_window_center(self):
        hwnd = win32gui.FindWindow(None, WIN_TITLE)
        if not hwnd:
            print(f"未找到窗口: {WIN_TITLE}")
            return None, None
        rect = win32gui.GetWindowRect(hwnd)
        left, top, right, bottom = rect
        cx = left + (right - left) // 2
        cy = top + (bottom - top) // 2
        return cx, cy

    def on_press(self, key):
        try:
            if key == keyboard.Key.f8:
                if not self.is_recording:
                    cx, cy = self.get_window_center()
                    if cx is None: return
                    self.center_x, self.center_y = cx, cy
                    self.points = []
                    self.is_recording = True
                    print("\n>>> 开始录制... 请在角色前方划出你想要的扫瞄轨迹。")
                else:
                    self.is_recording = False
                    self.save_path()
                    print(f">>> 录制结束。已保存 {len(self.points)} 个点到 {SAVE_FILE}")
        except Exception as e:
            print(f"出错: {e}")

    def save_path(self):
        # 稀疏处理：每隔几个点取一个，防止点位过密影响性能
        step = 3 
        processed_points = self.points[::step]
        with open(SAVE_FILE, 'w') as f:
            json.dump(processed_points, f)

    def run(self):
        print(f"--- 鼠标轨迹录制工具 ---")
        print(f"1. 运行游戏并确保处于窗口/全屏窗口化模式。")
        print(f"2. 按下 [F8] 开始录制。")
        print(f"3. 均匀、平滑地移动鼠标，划出你想要的拾取扫瞄范围。")
        print(f"4. 再次按 [F8] 保存并退出。")
        
        listener = keyboard.Listener(on_press=self.on_press)
        listener.start()
        
        try:
            while True:
                if self.is_recording:
                    x, y = win32api.GetCursorPos()
                    # 记录相对于中心的偏移量
                    dx = x - self.center_x
                    dy = y - self.center_y
                    self.points.append((dx, dy))
                time.sleep(0.02)
        except KeyboardInterrupt:
            pass

if __name__ == "__main__":
    PathRecorder().run()
