import sys
import time
import ctypes
import numpy as np
from PIL import Image

sys.path.insert(0, ".")

from src.common.win32_window import find_poe2_window, ensure_window_focus, is_poe2_window_focused, get_client_rect
import src.common.win32_input as win32_input
from src.common.screen_capture import capture_window_bitblt, capture_rect_bitblt

def test():
    hwnd = find_poe2_window()
    print(f"HWND: {hex(hwnd) if hwnd else 0}")
    if not hwnd:
        return
    
    cl, ct, cw, ch = get_client_rect(hwnd)
    print(f"Client rect: ({cl}, {ct}, {cw}, {ch})")

    # Đưa cửa sổ lên foreground
    f_ok = ensure_window_focus(hwnd)
    print(f"ensure_window_focus: {f_ok}")
    time.sleep(0.5)

    is_f = is_poe2_window_focused(hwnd)
    print(f"is_poe2_window_focused: {is_f}")

    # Chụp ảnh trước
    img1 = capture_rect_bitblt(cl, ct, cw, ch)
    if img1:
        img1.save("captures/wasd_move_test_before.png")
        print("Đã lưu captures/wasd_move_test_before.png")

    print("Thực hiện send_wasd_direction phím W (1.0, 1.0) trong 1.5s...")
    ret = win32_input.send_wasd_direction(1.0, 1.0, dwell_ms=1.5, hwnd=hwnd)
    print(f"send_wasd_direction ret: {ret}")

    time.sleep(0.5)

    # Chụp ảnh sau
    img2 = capture_rect_bitblt(cl, ct, cw, ch)
    if img2:
        img2.save("captures/wasd_move_test_after.png")
        print("Đã lưu captures/wasd_move_test_after.png")

    if img1 and img2:
        diff = np.abs(np.array(img1).astype(float) - np.array(img2).astype(float)).mean()
        print(f"Diff: {diff:.2f}")

if __name__ == "__main__":
    test()
