import sys
import os
import time
import ctypes
from pathlib import Path
from PIL import Image
import numpy as np

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

from src.assistant_tool.client_launcher import Poe2ClientLauncher
from src.common.win32_window import find_poe2_window, ensure_window_focus, get_client_rect, is_poe2_window_focused, attach_to_default_desktop, attach_to_window_desktop
import src.common.win32_input as win32_input
import scripts.reconnect_and_enter_hideout as reconnect_module

def run_test():
    print("=" * 60)
    print("TEST ISOLATED WASD MOVEMENT IN SHORELINE HIDEOUT (FULL IN-GAME)")
    print("=" * 60)

    hwnd = find_poe2_window()
    if not hwnd:
        print("Khởi chạy POE2 client...")
        Poe2ClientLauncher.launch_client(wait_timeout_sec=60)
        start_w = time.time()
        while time.time() - start_w < 60:
            hwnd = find_poe2_window()
            if hwnd:
                break
            time.sleep(1.0)

    if not hwnd:
        print("Không tìm thấy POE2 HWND!")
        return

    print(f"POE2 HWND: {hex(hwnd)}")
    attach_to_default_desktop()
    time.sleep(1.0)

    # Đảm bảo nhân vật đã vào Hideout
    rc_result = reconnect_module.main(hwnd=hwnd)
    print(f"Reconnect result: {rc_result.get('success')}")

    time.sleep(3.0)
    attach_to_window_desktop(hwnd)

    cl, ct, cw, ch = get_client_rect(hwnd)
    print(f"ClientRect: {cl}, {ct}, {cw}x{ch}")

    # Focus POE2
    foc_ok = ensure_window_focus(hwnd, timeout_ms=2000)
    print(f"ensure_window_focus result: {foc_ok}")

    user32 = ctypes.windll.user32
    fg = user32.GetForegroundWindow()
    print(f"Current FG HWND: {hex(fg)}, Is POE2 FG: {fg == hwnd}")
    print(f"is_poe2_window_focused: {is_poe2_window_focused(hwnd)}")

    from src.assistant_tool.screen_capturer import ScreenCapturer
    capturer = ScreenCapturer(output_dir="captures/wasd_test")

    # Dismiss modals
    win32_input.press_key(0x1B, 0x01, delay_after=0.3, hwnd=hwnd)
    win32_input.press_key(0x20, 0x39, delay_after=0.3, hwnd=hwnd)

    cap_before = capturer.capture_screenshot("BEFORE_WASD_IN_GAME", capture_ram=False)
    print(f"Captured BEFORE: {cap_before}")

    # Bấm giữ phím S (đi xuống dưới bãi biển) trong 2.0s
    print("Gửi phím S (đi xuống) trong 2.0s...")
    res = win32_input.send_wasd_direction(0.0, -1.0, dwell_ms=2.0, hwnd=hwnd)
    print(f"send_wasd_direction returned: {res}")

    time.sleep(0.5)
    cap_after = capturer.capture_screenshot("AFTER_WASD_S_IN_GAME", capture_ram=False)
    print(f"Captured AFTER: {cap_after}")

    if cap_before and cap_after and os.path.exists(cap_before) and os.path.exists(cap_after):
        img1 = np.array(Image.open(cap_before).convert('L'))
        img2 = np.array(Image.open(cap_after).convert('L'))
        diff = float(np.mean(np.abs(img1.astype(float) - img2.astype(float))))
        print(f"==> PIXEL DIFF SAU PHÍM S: {diff:.2f}")
        if diff > 15.0:
            print(f"🎉 THÀNH CÔNG RỰC RỠ: Nhân vật đã thực sự di chuyển trên màn hình! (Diff = {diff:.2f})")
        else:
            print(f"⚠️ CẢNH BÁO: Nhân vật chưa di chuyển đủ rõ rệt (diff = {diff:.2f} <= 15).")

if __name__ == "__main__":
    run_test()
