import sys
sys.path.insert(0, ".")
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")
import time
import winocr
from PIL import ImageGrab
import src.common as common
from src.common.win32_window import find_poe2_window, ensure_window_focus, get_client_rect

hwnd = find_poe2_window()
if not hwnd:
    print("POE2 window not found!")
    exit(1)

ensure_window_focus(hwnd)
time.sleep(0.3)
cl, ct, cw, ch = get_client_rect(hwnd)

# Mở World Map bằng phím U
print("Gửi phím U...")
common.press_key(0x55, 0x16, delay_after=1.2)

img = ImageGrab.grab(bbox=(cl, ct, cl + cw, ct + ch))
img.save("captures/test_u_map.png")
print("Saved test_u_map.png")

res = winocr.recognize_pil_sync(img)
words = [
    w for l in res.get("lines", [])
    for w in l.get("words", [])
    if any(k in w["text"].upper() for k in ["END", "GAME", "ENIX", ";AME"])
]
print("Found words:", words)

if words:
    target_w = words[0]
    wx = int(target_w["bounding_rect"]["x"] + target_w["bounding_rect"]["width"] / 2)
    wy = int(target_w["bounding_rect"]["y"] + target_w["bounding_rect"]["height"] / 2)
    print(f"Clicking ENDGAME at ({wx}, {wy}) with screen pos ({cl + wx}, {ct + wy})...")
    common.click(cl + wx, ct + wy, hold_ms=0.1, delay_after=1.2)

    img2 = ImageGrab.grab(bbox=(cl, ct, cl + cw, ct + ch))
    img2.save("captures/test_after_click_endgame.png")
    print("Saved test_after_click_endgame.png")
else:
    print("No ENDGAME words found!")
