import time
import ctypes
import sys

user32 = ctypes.windll.user32

def main():
    try:
        hwinsta = user32.OpenWindowStationW("WinSta0", False, 0x10000000)
        if hwinsta: user32.SetProcessWindowStation(hwinsta)
        hdesk = user32.OpenDesktopW("Default", 0, False, 0x10000000)
        if hdesk: user32.SetThreadDesktop(hdesk)
    except Exception as e:
        print(f"Desktop error: {e}")

    hwnd = user32.FindWindowW("POEWindowClass", None)
    if not hwnd: hwnd = user32.FindWindowW(None, "Path of Exile 2")
    if not hwnd: return

    user32.ShowWindow(hwnd, 9)
    user32.SetForegroundWindow(hwnd)
    time.sleep(0.3)

    # Click title bar to focus
    user32.SetCursorPos(1280, 5)
    time.sleep(0.05)
    user32.mouse_event(0x0002, 0, 0, 0, 0)
    time.sleep(0.05)
    user32.mouse_event(0x0004, 0, 0, 0, 0)
    time.sleep(0.3)

    # Send ESC (VK 0x1B, scan 0x01)
    print("Sending ESC to close Options...")
    user32.keybd_event(0x1B, 0x01, 0, 0)
    time.sleep(0.08)
    user32.keybd_event(0x1B, 0x01, 2, 0)
    time.sleep(0.6)

    # Capture screen
    sys.path.insert(0, r"C:\Projects\AutoPOE2")
    from tools.autonomous_map_runner import ScreenCapturerGDI
    c = ScreenCapturerGDI()
    c.capture(r"C:\Projects\AutoPOE2\captures\test_esc_after.png")
    print("Captured test_esc_after.png")

if __name__ == "__main__":
    main()
