# -*- coding: utf-8 -*-
"""
APEX 入力レコーダー（APEX 入力シミュレーター用）
キーボード・マウスボタン・ホイール・マウス移動（視点移動）を記録します。

使い方:
  1. pip install pynput
  2. OBS の [設定] > [ホットキー] で「録画開始」を F9、「録画終了」を F10 に設定
     （録画形式は mp4 推奨）
  3. このスクリプトを起動したまま APEX をプレイ
  4. F9 で OBS の録画と入力の記録が同時に始まり、F10 で両方止まります
  5. 同じフォルダに apex_keys_YYYYmmdd_HHMMSS.json が保存されます

  Ctrl+C でスクリプト終了。F9/F10 は何度でも繰り返せます。
  入力が記録されない場合は、管理者権限のターミナルで実行してみてください。

マウス移動について:
  Windows では Raw Input（マウスの生の移動量）を読むため、ゲームがカーソルを
  固定していても視点移動を記録できます。値はマウスのカウント（DPI 単位）です。
"""
import ctypes
import json
import sys
import threading
import time
from datetime import datetime

from pynput import keyboard, mouse

START_KEY = keyboard.Key.f9
STOP_KEY = keyboard.Key.f10
MOVE_BIN = 0.01  # マウス移動を 10ms ごとにまとめる

SPECIAL = {
    keyboard.Key.space: "Space",
    keyboard.Key.ctrl_l: "ControlLeft", keyboard.Key.ctrl_r: "ControlRight",
    keyboard.Key.ctrl: "ControlLeft",
    keyboard.Key.shift: "ShiftLeft", keyboard.Key.shift_l: "ShiftLeft",
    keyboard.Key.shift_r: "ShiftRight",
    keyboard.Key.alt_l: "AltLeft", keyboard.Key.alt_r: "AltRight",
    keyboard.Key.alt: "AltLeft",
    keyboard.Key.tab: "Tab", keyboard.Key.caps_lock: "CapsLock",
    keyboard.Key.esc: "Escape", keyboard.Key.enter: "Enter",
}
BUTTONS = {"left": "MouseLeft", "right": "MouseRight", "middle": "MouseMiddle",
           "x1": "MouseX1", "x2": "MouseX2"}

lock = threading.Lock()
events = []
held = set()
t0 = None  # None のとき記録していない
move_bin = None  # [bin番号, dx, dy]


def to_code(key):
    """pynput のキーをブラウザの KeyboardEvent.code 形式に変換"""
    if key in SPECIAL:
        return SPECIAL[key]
    vk = getattr(key, "vk", None)
    if vk is not None:
        if 0x41 <= vk <= 0x5A:
            return "Key" + chr(vk)
        if 0x30 <= vk <= 0x39:
            return "Digit" + chr(vk)
    ch = getattr(key, "char", None)
    if ch:
        if ch.isalpha():
            return "Key" + ch.upper()
        if ch.isdigit():
            return "Digit" + ch
        return ch
    return str(key).replace("Key.", "")


def now():
    return round(time.perf_counter() - t0, 4)


def flush_move():
    """まとめたマウス移動を 1 件のイベントとして書き出す（lock 内で呼ぶ）"""
    global move_bin
    if move_bin and (move_bin[1] or move_bin[2]):
        events.append({"t": round(move_bin[0] * MOVE_BIN + MOVE_BIN / 2, 4),
                       "type": "move", "code": "Mouse",
                       "dx": move_bin[1], "dy": move_bin[2]})
    move_bin = None


def add_move(dx, dy):
    global move_bin
    with lock:
        if t0 is None:
            return
        b = int((time.perf_counter() - t0) / MOVE_BIN)
        if move_bin and move_bin[0] != b:
            flush_move()
        if not move_bin:
            move_bin = [b, 0, 0]
        move_bin[1] += dx
        move_bin[2] += dy


def save():
    name = datetime.now().strftime("apex_keys_%Y%m%d_%H%M%S.json")
    events.sort(key=lambda e: e["t"])
    data = {"format": "apex-keylog", "version": 2, "source": "pynput",
            "events": events}
    with open(name, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, separators=(",", ":"))
    moves = sum(1 for e in events if e["type"] == "move")
    print(f"■ 記録終了: 入力 {len(events) - moves} 件 / 視点移動 {moves} 件 → {name}")


# ---------- キーボード ----------
def on_press(key):
    global t0, events
    with lock:
        if key == START_KEY and t0 is None:
            t0 = time.perf_counter()
            events = []
            held.clear()
            print("● 記録開始（F10 で終了）")
            return
        if key == STOP_KEY and t0 is not None:
            flush_move()
            for code in list(held):  # 押しっぱなしの入力を閉じる
                events.append({"t": now(), "type": "up", "code": code})
            held.clear()
            t0 = None
            save()
            return
        if t0 is None:
            return
        code = to_code(key)
        if code in held:  # OS のキーリピートを無視
            return
        held.add(code)
        events.append({"t": now(), "type": "down", "code": code})


def on_release(key):
    with lock:
        if t0 is None:
            return
        code = to_code(key)
        if code not in held:
            return
        held.discard(code)
        events.append({"t": now(), "type": "up", "code": code})


# ---------- マウスボタン・ホイール ----------
def on_click(x, y, button, pressed):
    code = BUTTONS.get(getattr(button, "name", ""))
    if not code:
        return
    with lock:
        if t0 is None:
            return
        if pressed and code not in held:
            held.add(code)
            events.append({"t": now(), "type": "down", "code": code})
        elif not pressed and code in held:
            held.discard(code)
            events.append({"t": now(), "type": "up", "code": code})


def on_scroll(x, y, dx, dy):
    with lock:
        if t0 is None or dy == 0:
            return
        code = "WheelUp" if dy > 0 else "WheelDown"
        for _ in range(abs(int(dy)) or 1):
            events.append({"t": now(), "type": "wheel", "code": code})


# ---------- マウス移動（Windows: Raw Input） ----------
def start_raw_mouse():
    from ctypes import wintypes
    user32 = ctypes.WinDLL("user32", use_last_error=True)
    kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)

    WM_INPUT = 0x00FF
    RIDEV_INPUTSINK = 0x00000100
    RID_INPUT = 0x10000003
    RIM_TYPEMOUSE = 0
    MOUSE_MOVE_ABSOLUTE = 0x01
    LRESULT = ctypes.c_ssize_t
    WNDPROC = ctypes.WINFUNCTYPE(LRESULT, wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM)

    class RAWINPUTDEVICE(ctypes.Structure):
        _fields_ = [("usUsagePage", wintypes.USHORT), ("usUsage", wintypes.USHORT),
                    ("dwFlags", wintypes.DWORD), ("hwndTarget", wintypes.HWND)]

    class RAWINPUTHEADER(ctypes.Structure):
        _fields_ = [("dwType", wintypes.DWORD), ("dwSize", wintypes.DWORD),
                    ("hDevice", wintypes.HANDLE), ("wParam", wintypes.WPARAM)]

    class RAWMOUSE(ctypes.Structure):
        _fields_ = [("usFlags", wintypes.USHORT), ("_pad", wintypes.USHORT),
                    ("usButtonFlags", wintypes.USHORT), ("usButtonData", wintypes.USHORT),
                    ("ulRawButtons", wintypes.ULONG), ("lLastX", wintypes.LONG),
                    ("lLastY", wintypes.LONG), ("ulExtraInformation", wintypes.ULONG)]

    class RAWINPUT(ctypes.Structure):
        _fields_ = [("header", RAWINPUTHEADER), ("mouse", RAWMOUSE)]

    class WNDCLASSW(ctypes.Structure):
        _fields_ = [("style", wintypes.UINT), ("lpfnWndProc", WNDPROC),
                    ("cbClsExtra", ctypes.c_int), ("cbWndExtra", ctypes.c_int),
                    ("hInstance", wintypes.HINSTANCE), ("hIcon", wintypes.HICON),
                    ("hCursor", wintypes.HANDLE), ("hbrBackground", wintypes.HBRUSH),
                    ("lpszMenuName", wintypes.LPCWSTR), ("lpszClassName", wintypes.LPCWSTR)]

    user32.DefWindowProcW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
    user32.DefWindowProcW.restype = LRESULT
    user32.GetRawInputData.argtypes = [wintypes.HANDLE, wintypes.UINT, ctypes.c_void_p,
                                       ctypes.POINTER(wintypes.UINT), wintypes.UINT]
    user32.GetRawInputData.restype = wintypes.UINT
    user32.CreateWindowExW.argtypes = [wintypes.DWORD, wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.DWORD,
                                       ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int,
                                       wintypes.HWND, wintypes.HMENU, wintypes.HINSTANCE, wintypes.LPVOID]
    user32.CreateWindowExW.restype = wintypes.HWND
    user32.RegisterRawInputDevices.argtypes = [ctypes.POINTER(RAWINPUTDEVICE), wintypes.UINT, wintypes.UINT]
    kernel32.GetModuleHandleW.restype = wintypes.HMODULE
    header_size = ctypes.sizeof(RAWINPUTHEADER)
    ready = threading.Event()
    result = {"ok": False}

    def wndproc(hwnd, msg, wparam, lparam):
        if msg == WM_INPUT:
            size = wintypes.UINT(0)
            user32.GetRawInputData(lparam, RID_INPUT, None, ctypes.byref(size), header_size)
            if size.value:
                buf = ctypes.create_string_buffer(size.value)
                if user32.GetRawInputData(lparam, RID_INPUT, buf, ctypes.byref(size), header_size) == size.value:
                    ri = ctypes.cast(buf, ctypes.POINTER(RAWINPUT)).contents
                    if ri.header.dwType == RIM_TYPEMOUSE and not (ri.mouse.usFlags & MOUSE_MOVE_ABSOLUTE):
                        dx, dy = ri.mouse.lLastX, ri.mouse.lLastY
                        if dx or dy:
                            add_move(dx, dy)
        return user32.DefWindowProcW(hwnd, msg, wparam, lparam)

    proc = WNDPROC(wndproc)  # 参照を保持して GC を防ぐ

    def run():
        hinst = kernel32.GetModuleHandleW(None)
        wc = WNDCLASSW()
        wc.lpfnWndProc = proc
        wc.hInstance = hinst
        wc.lpszClassName = "ApexRawMouseRecorder"
        user32.RegisterClassW(ctypes.byref(wc))
        hwnd = user32.CreateWindowExW(0, wc.lpszClassName, "", 0, 0, 0, 0, 0,
                                      wintypes.HWND(-3), None, hinst, None)  # メッセージ専用ウィンドウ
        rid = RAWINPUTDEVICE(0x01, 0x02, RIDEV_INPUTSINK, hwnd)  # 汎用デスクトップ / マウス
        result["ok"] = bool(hwnd) and bool(user32.RegisterRawInputDevices(ctypes.byref(rid), 1, ctypes.sizeof(rid)))
        ready.set()
        if not result["ok"]:
            return
        msg = wintypes.MSG()
        while user32.GetMessageW(ctypes.byref(msg), None, 0, 0) > 0:
            user32.TranslateMessage(ctypes.byref(msg))
            user32.DispatchMessageW(ctypes.byref(msg))

    th = threading.Thread(target=run, daemon=True)
    th.start()
    ready.wait(3)
    run.proc = proc
    return result["ok"]


def start_fallback_mouse():
    """Windows 以外: カーソル位置の差分から移動量を求める（ゲーム中は不正確）"""
    last = {"p": None}

    def on_move(x, y):
        p = last["p"]
        last["p"] = (x, y)
        if p:
            add_move(x - p[0], y - p[1])
    return on_move


if __name__ == "__main__":
    on_move = None
    if sys.platform == "win32":
        if start_raw_mouse():
            print("マウス移動: Raw Input で記録します")
        else:
            print("警告: Raw Input を開始できませんでした。マウス移動は記録されません")
    else:
        on_move = start_fallback_mouse()
        print("警告: Windows 以外のため、マウス移動はカーソル位置から近似します")

    print("待機中… F9 で記録開始 / F10 で記録終了 / Ctrl+C で終了")
    ml = mouse.Listener(on_click=on_click, on_scroll=on_scroll, on_move=on_move)
    ml.start()
    with keyboard.Listener(on_press=on_press, on_release=on_release) as kl:
        try:
            kl.join()
        except KeyboardInterrupt:
            pass
