import time
import ctypes
from ctypes import wintypes
import sys
from pathlib import Path
from PIL import Image, ImageChops, ImageStat

sys.path.insert(0, str(Path(".").resolve()))
from src.common.win32_window import find_poe2_window, attach_to_window_desktop, ensure_window_focus, is_poe2_window_focused
from src.common.win32_input import (
    INPUT, INPUT_KEYBOARD, KEYEVENTF_SCANCODE, KEYEVENTF_KEYUP,
    VK_W, SC_W, VK_A, SC_A, send_wasd_direction
)
from src.common.screen_capture import capture_window_bitblt
import src.common.vision_ocr as vision_ocr

hwnd = find_poe2_window()
print(f"POE2 HWND: {hex(hwnd) if hwnd else None}")
if not hwnd:
    sys.exit(1)

attach_to_window_desktop(hwnd)
focused = ensure_window_focus(hwnd)
time.sleep(0.5)

user32 = ctypes.windll.user32
fg = user32.GetForegroundWindow()
is_focused = is_poe2_window_focused(hwnd)
print(f"Foreground HWND: {hex(fg)}, Target HWND: {hex(hwnd)}, is_poe2_window_focused: {is_focused}")

img_before = capture_window_bitblt(hwnd, client_only=True)
img_before.save("captures/probe_live_before.png")

# Method: Test send_wasd_direction with dwell 1.5s
print("Testing send_wasd_direction(1.0, 1.0, dwell_ms=1.5)...")
ok = send_wasd_direction(1.0, 1.0, dwell_ms=1.5, hwnd=hwnd)
print(f"send_wasd_direction returned: {ok}")

time.sleep(0.5)
img_after = capture_window_bitblt(hwnd, client_only=True)
img_after.save("captures/probe_live_after.png")

diff = ImageChops.difference(img_before, img_after)
stat = ImageStat.Stat(diff)
print("Pixel diff mean:", stat.mean)

# OCR positions before and after
res_b = vision_ocr.safe_recognize_pil_sync(img_before)
res_a = vision_ocr.safe_recognize_pil_sync(img_after)

def extract_pos(res):
    pos = {}
    for l in res.get("lines", []):
        for k in ["MAP DEVICE", "WAYPOINT", "ANGE", "WELL"]:
            if k in l.get("text", "").upper():
                words = l.get("words", [])
                if words:
                    r = words[0].get("bounding_rect", {})
                    pos[k] = (r.get("x"), r.get("y"))
    return pos

print("Before:", extract_pos(res_b))
print("After :", extract_pos(res_a))
