import os
import sys
import time
from PIL import Image

sys.path.insert(0, ".")

from src.assistant_tool.client_launcher import Poe2ClientLauncher
from src.common.win32_window import find_poe2_window, ensure_window_focus, is_poe2_window_focused, get_client_rect
import src.common.win32_input as win32_input
import src.common.vision_ocr as vision_ocr
from src.common.screen_capture import capture_window_bitblt
import scripts.reconnect_and_enter_hideout as reconnect_module

def main():
    print("=== KIỂM THỬ CLICK TƯƠNG TÁC TRỰC TIẾP MAP DEVICE ===", flush=True)
    hwnd = find_poe2_window()
    if not hwnd:
        Poe2ClientLauncher.launch_client(wait_timeout_sec=90)
        for _ in range(90):
            hwnd = find_poe2_window()
            if hwnd:
                break
            time.sleep(1.0)

    rc = reconnect_module.main(hwnd=hwnd)
    print(f"Reconnect status: {rc.get('success')}", flush=True)

    time.sleep(3.0)
    ensure_window_focus(hwnd)
    time.sleep(0.5)

    cl, ct, cw, ch = get_client_rect(hwnd)
    print(f"Game HWND: 0x{hwnd:X}, Focused: {is_poe2_window_focused(hwnd)}, Rect: ({cl}, {ct}, {cw}x{ch})", flush=True)

    # Chụp ảnh ban đầu tại Waypoint
    img_before = capture_window_bitblt(hwnd, client_only=True)
    if img_before:
        img_before.save("captures/direct_test_1_before.png")

    # Hover vào nhãn MAP DEVICE tại (310, 173) client coord
    target_client_x, target_client_y = 310, 173
    target_screen_x = cl + target_client_x
    target_screen_y = ct + target_client_y

    print(f"Hover vào nhãn MAP DEVICE tại screen ({target_screen_x}, {target_screen_y})...", flush=True)
    win32_input.hover(target_screen_x, target_screen_y, delay_after=0.3, hwnd=hwnd)

    img_hover = capture_window_bitblt(hwnd, client_only=True)
    if img_hover:
        img_hover.save("captures/direct_test_2_hover.png")

    print(f"Click chuột trái vào nhãn MAP DEVICE tại screen ({target_screen_x}, {target_screen_y})...", flush=True)
    win32_input.click(target_screen_x, target_screen_y, hold_ms=0.06, delay_after=0.1, hwnd=hwnd)

    # Chờ nhân vật tự động pathfind đến Map Device và mở Atlas UI (chụp frame mỗi 1s)
    for sec in range(1, 6):
        time.sleep(1.0)
        img_step = capture_window_bitblt(hwnd, client_only=True)
        if img_step:
            step_path = f"captures/direct_test_step_{sec}s.png"
            img_step.save(step_path)
            res = vision_ocr.safe_recognize_pil_sync(img_step)
            txt = " ".join(l.get("text", "") for l in res.get("lines", [])).upper()
            is_open = any(k in txt for k in ["TRAVERSE", "ENDGAME", "INTERLUDE", "ACT 1", "SEARCH", "WAYSTONE", "ATLAS"])
            print(f"Giây thứ {sec}: Atlas open = {is_open} (Tokens: {txt[:80]}...)", flush=True)
            if is_open:
                print(f"🎉 THÀNH CÔNG RỰC RỠ: Atlas UI ĐÃ MỞ TỰ ĐỘNG sau {sec}s!", flush=True)
                break

if __name__ == "__main__":
    main()
