import os
import sys
import time
import ctypes

sys.path.insert(0, r"c:\Projects\AutoPOE2")
from src.common.win32_window import attach_to_default_desktop, find_poe2_window
from src.common.virtual_display_manager import capture_virtual_display
from src.common.win32_input import post_message_click
from src.assistant_tool.optical_inventory_scanner import OpticalInventoryScanner

attach_to_default_desktop()
hwnd = find_poe2_window()
user32 = ctypes.windll.user32

VK_ESCAPE = 0x1B
SC_ESCAPE = 0x01
VK_I = 0x49
SC_I = 0x17
VK_SPACE = 0x20
SC_SPACE = 0x39
WM_KEYDOWN = 0x0100
WM_KEYUP = 0x0101

print("1. Dismissing 'DESTROY' prompt with Escape...")
user32.PostMessageW(hwnd, WM_KEYDOWN, VK_ESCAPE, (SC_ESCAPE << 16) | 1)
time.sleep(0.05)
user32.PostMessageW(hwnd, WM_KEYUP, VK_ESCAPE, (SC_ESCAPE << 16) | 0xC0000001)
time.sleep(0.3)

print("2. Opening Inventory with 'I'...")
user32.PostMessageW(hwnd, WM_KEYDOWN, VK_I, (SC_I << 16) | 1)
time.sleep(0.05)
user32.PostMessageW(hwnd, WM_KEYUP, VK_I, (SC_I << 16) | 0xC0000001)
time.sleep(0.8)

img_inv = capture_virtual_display()
img_inv.save("captures/inv_cursor_check.png")

scanner = OpticalInventoryScanner(1920, 1080)
# Find an empty slot in the inventory
# Inventory grid is typically on the right side of the screen
empty_slot = None
for r in range(4, -1, -1): # search from bottom rows first
    for c in range(11, -1, -1):
        if scanner.is_slot_empty(img_inv, r, c):
            empty_slot = (r, c)
            break
    if empty_slot:
        break

print(f"Found empty slot: {empty_slot}")
if empty_slot:
    sx, sy = scanner.get_slot_screen_pos(empty_slot[0], empty_slot[1])
    print(f"Clicking empty slot at ({sx}, {sy}) to deposit held item...")
    post_message_click(hwnd, sx, sy, button="left", hold_ms=0.08, delay_after=0.5)

img_after_deposit = capture_virtual_display()
img_after_deposit.save("captures/inv_after_deposit.png")

print("3. Closing Inventory with Space...")
user32.PostMessageW(hwnd, WM_KEYDOWN, VK_SPACE, (SC_SPACE << 16) | 1)
time.sleep(0.05)
user32.PostMessageW(hwnd, WM_KEYUP, VK_SPACE, (SC_SPACE << 16) | 0xC0000001)
time.sleep(0.5)

img_final = capture_virtual_display()
img_final.save("captures/after_cursor_cleared.png")
print("Done clearing cursor item!")
