import time
import ctypes
from ctypes import wintypes
import urllib.request

from src.common.win32_window import find_poe2_window, ensure_window_focus, is_poe2_window_focused
import src.common.vision_ocr as vision_ocr

user32 = ctypes.windll.user32
hwnd = find_poe2_window()
print(f"PoE2 HWND: {hwnd}")

# 1. Save user cursor and foreground window
orig_fg = user32.GetForegroundWindow()
orig_pt = wintypes.POINT()
user32.GetCursorPos(ctypes.byref(orig_pt))
print(f"User cursor: ({orig_pt.x}, {orig_pt.y}), fg HWND: {orig_fg}")

# 2. Map Device screen pos on Monitor 2 (1920 + 620, 272)
target_sx = 1920 + 620
target_sy = 272

try:
    print("Activating POE2 focus per Doc 74 Alt-Key Bypass...")
    ensure_window_focus(hwnd, timeout_ms=800)
    print(f"Focused: {is_poe2_window_focused(hwnd)}")
    
    # 3. Synchronize hardware cursor per INV-DX12-HARDWARE-RAYCAST
    user32.SetCursorPos(target_sx, target_sy)
    time.sleep(0.08) # Wait for DX12 camera raycast
    
    MOUSEEVENTF_LEFTDOWN = 0x0002
    MOUSEEVENTF_LEFTUP = 0x0004
    user32.mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    time.sleep(0.06)
    user32.mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
    print(f"Clicked Map Device at screen ({target_sx}, {target_sy})")
    time.sleep(0.1)
finally:
    # 4. Restore user cursor and focus
    user32.SetCursorPos(orig_pt.x, orig_pt.y)
    if orig_fg and orig_fg != hwnd:
        user32.SetForegroundWindow(orig_fg)
    print("Restored user cursor and focus.")

# Wait 2.5s for character to walk to Map Device and open UI
time.sleep(2.5)
urllib.request.urlretrieve("http://127.0.0.1:8088/preview.jpg", "captures/test_dx12_raycast_result.jpg")
print("Saved captures/test_dx12_raycast_result.jpg")

is_open = vision_ocr.is_atlas_ui_open("captures/test_dx12_raycast_result.jpg")
print(f"Result: is_atlas_ui_open = {is_open}")
