import os
import sys
import time
import ctypes
from pathlib import Path

sys.path.insert(0, str(Path(".").resolve()))

from src.assistant_tool.client_launcher import Poe2ClientLauncher
from src.common.win32_window import find_poe2_window, ensure_window_focus, is_poe2_window_focused, get_client_rect
import scripts.reconnect_and_enter_hideout as reconnect_module
from src.assistant_tool.screen_capturer import ScreenCapturer
import src.common.vision_ocr as vision_ocr
from PIL import Image

print("=== TEST WASD STEP BY STEP ===")

hwnd = find_poe2_window()
if not hwnd:
    print("Launching game client...")
    Poe2ClientLauncher.launch_client(wait_timeout_sec=90)
    time.sleep(5)
    hwnd = find_poe2_window()

print(f"HWND: {hex(hwnd) if hwnd else None}")
if not hwnd:
    print("Failed to get HWND!")
    sys.exit(1)

# Reconnect if not in hideout
capturer = ScreenCapturer(output_dir="captures/live_test")
cap_init = capturer.capture_screenshot(event_name="STEP_INIT", capture_ram=False, auto_focus=False, background_mode=True)
img_init = Image.open(cap_init)
res_init = vision_ocr.safe_recognize_pil_sync(img_init)
txt_init = " ".join(l.get("text", "") for l in res_init.get("lines", [])).upper()

if "SHIELD" not in txt_init and "WAYPOINT" not in txt_init and "MAP DEVICE" not in txt_init and "WARD" not in txt_init:
    print("Reconnecting to Hideout...")
    reconnect_module.main(hwnd=hwnd)
    time.sleep(3)

ensure_window_focus(hwnd)
time.sleep(0.5)

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

# Đặt chuột an toàn ở bên trong client area
user32 = ctypes.windll.user32
safe_mx = cl + cw // 2
safe_my = ct + ch // 4  # Phía trên nhân vật (hướng Bắc)
user32.SetCursorPos(safe_mx, safe_my)
time.sleep(0.2)

def get_labels(img_path):
    img = Image.open(img_path)
    res = vision_ocr.safe_recognize_pil_sync(img)
    labels = {}
    for l in res.get("lines", []):
        for name in ["MAP DEVICE", "WAYPOINT", "ANGE", "WELL"]:
            if name in l.get("text", "").upper():
                words = l.get("words", [])
                if words:
                    r = words[0].get("bounding_rect", {})
                    labels[name] = (r.get("x"), r.get("y"))
    return labels

cap_0 = capturer.capture_screenshot(event_name="STEP_BEFORE_MOVE", capture_ram=False, auto_focus=False, background_mode=True)
lbl_0 = get_labels(cap_0)
print("Labels ban đầu:", lbl_0)

# THỬ NGHIỆM 1: keybd_event thuần túy nhấn phím W (0x57, scancode 0x11) trong 2.0s
print("\n--- TEST 1: keybd_event VK_W hold 2.0s (Hướng Bắc) ---")
user32.keybd_event(0x57, 0x11, 0, 0)
time.sleep(2.0)
user32.keybd_event(0x57, 0x11, 2, 0)
time.sleep(0.5)

cap_1 = capturer.capture_screenshot(event_name="STEP_AFTER_TEST1", capture_ram=False, auto_focus=False, background_mode=True)
lbl_1 = get_labels(cap_1)
print("Labels sau Test 1:", lbl_1)

# THỬ NGHIỆM 2: keybd_event nhấn phím A (0x41, scancode 0x1E) trong 2.0s (Hướng Tây)
print("\n--- TEST 2: keybd_event VK_A hold 2.0s (Hướng Tây) ---")
user32.keybd_event(0x41, 0x1E, 0, 0)
time.sleep(2.0)
user32.keybd_event(0x41, 0x1E, 2, 0)
time.sleep(0.5)

cap_2 = capturer.capture_screenshot(event_name="STEP_AFTER_TEST2", capture_ram=False, auto_focus=False, background_mode=True)
lbl_2 = get_labels(cap_2)
print("Labels sau Test 2:", lbl_2)

# THỬ NGHIỆM 3: Gửi qua send_wasd_direction chuẩn của project
print("\n--- TEST 3: send_wasd_direction(dx=1.0, dy=1.0, dwell_ms=2.0) ---")
import src.common.win32_input as win32_input
res_wasd = win32_input.send_wasd_direction(1.0, 1.0, dwell_ms=2.0, hwnd=hwnd)
print("send_wasd_direction returned:", res_wasd)
time.sleep(0.5)

cap_3 = capturer.capture_screenshot(event_name="STEP_AFTER_TEST3", capture_ram=False, auto_focus=False, background_mode=True)
lbl_3 = get_labels(cap_3)
print("Labels sau Test 3:", lbl_3)

print("\n=== TỔNG HỢP BIẾN ĐỔI TỌA ĐỘ ===")
for k in ["WAYPOINT", "MAP DEVICE", "ANGE", "WELL"]:
    p0 = lbl_0.get(k)
    p1 = lbl_1.get(k)
    p2 = lbl_2.get(k)
    p3 = lbl_3.get(k)
    print(f"  {k:12s}: Init={p0} -> T1(W)={p1} -> T2(A)={p2} -> T3(WASD)={p3}")
