import time
import sys
from pathlib import Path
from PIL import Image

try:
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(encoding="utf-8")
except Exception:
    pass

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

from src.common.win32_window import find_poe2_window, ensure_window_focus, get_client_rect
from src.common.win32_input import hover, click
from src.common.screen_capture import capture_window_bitblt
import src.common.vision_ocr as vo

hwnd = find_poe2_window()
ensure_window_focus(hwnd)
cl, ct, cw, ch = get_client_rect(hwnd)
print(f"Scanning grid on HWND 0x{hwnd:X}, Rect: ({cl}, {ct}, {cw}x{ch})")

found = None
for x in range(int(cw * 0.25), int(cw * 0.75), 80):
    for y in range(int(ch * 0.15), int(ch * 0.70), 70):
        hover(cl + x, ct + y, delay_after=0.12)
        img = capture_window_bitblt(hwnd, client_only=True)
        if not img:
            continue
        res = vo.safe_recognize_pil_sync(img)
        labels = [l.get("text") for l in res.get("lines", []) if any(k in l.get("text", "").upper() for k in ["MAP", "DEVICE", "STASH", "WAYPOINT", "ANGE", "WELL", "DORYANI", "ZELINA"])]
        if labels:
            print(f"🎯 Found object at ({x}, {y}): {labels}")
            found = (x, y, labels)
            img.save("captures/grid_found.png")
            if any("MAP" in l.upper() for l in labels) or any("DEVICE" in l.upper() for l in labels):
                print(f"🌟 FOUND MAP DEVICE AT ({x}, {y})!")
                break
    if found and any("MAP" in l.upper() for l in found[2]):
        break

print("Grid scan completed. Best result:", found)
