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

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

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

def test_nav():
    print("=== TEST ĐIỀU HƯỚNG TIẾP CẬN VÀ MỞ MAP DEVICE ===")
    hwnd = find_poe2_window()
    if not hwnd:
        print("Khởi chạy client POE2...")
        Poe2ClientLauncher.launch_client(wait_timeout_sec=90)
        for _ in range(90):
            hwnd = find_poe2_window()
            if hwnd:
                break
            time.sleep(1.0)
    if not hwnd:
        print("Không tìm thấy HWND POE2!")
        return False

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

    ensure_window_focus(hwnd)
    time.sleep(1.0)
    cl, ct, cw, ch = get_client_rect(hwnd)
    print(f"HWND: 0x{hwnd:X}, Rect: ({cl}, {ct}, {cw}x{ch})")

    # Đóng modal/menu nếu có
    win32_input.press_key(0x1B, 0x01, delay_after=0.25)
    win32_input.press_key(0x20, 0x39, delay_after=0.25)

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

    # Nhịp 1: Đi thoát vành đá sang dải cát Đông Bắc (phím W + D, dwell 0.6s)
    # Trong send_wasd_direction:
    # W + D tương ứng dx=0, dy=1 hoặc gửi trực tiếp phím W (0x57) và D (0x44)
    print("Nhịp 1: Đi vòng qua dải cát phía trên (W + D 0.6s)...")
    win32_input.press_key(0x57, 0x11, hold_ms=0.6, delay_after=0.1) # Phím W
    win32_input.press_key(0x44, 0x20, hold_ms=0.6, delay_after=0.2) # Phím D
    time.sleep(0.3)

    # Nhịp 2: Đi thẳng hướng Tây Bắc lên bệ đá Map Device (phím W + A 1.2s)
    print("Nhịp 2: Tiến thẳng lên bệ đá Map Device (W + A 1.2s)...")
    # Giữ đồng thời W và A
    user32 = win32_input._user32
    user32.keybd_event(0x57, 0x11, 0, 0) # W down
    user32.keybd_event(0x41, 0x1E, 0, 0) # A down
    time.sleep(1.2)
    user32.keybd_event(0x57, 0x11, win32_input.KEYEVENTF_KEYUP, 0) # W up
    user32.keybd_event(0x41, 0x1E, win32_input.KEYEVENTF_KEYUP, 0) # A up
    time.sleep(0.5)

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

    # Quét vị trí Map Device sau tiếp cận
    res_nav = vision_ocr.safe_recognize_pil_sync(img_after_nav)
    map_device_pos = None
    for l in res_nav.get("lines", []):
        t = l.get("text", "").upper()
        if "MAP" in t and "DEV" in t:
            words = [w for w in l.get("words", []) if any(k in w.get("text","").upper() for k in ["MAP", "DEV"])]
            if words:
                min_x = min(w["bounding_rect"]["x"] for w in words)
                max_x = max(w["bounding_rect"]["x"] + w["bounding_rect"]["width"] for w in words)
                min_y = min(w["bounding_rect"]["y"] for w in words)
                max_y = max(w["bounding_rect"]["y"] + w["bounding_rect"]["height"] for w in words)
                map_device_pos = (int((min_x + max_x) / 2), int((min_y + max_y) / 2))
                break

    cx, cy = cw / 2.0, ch / 2.0
    print(f"Vị trí Map Device sau tiếp cận: {map_device_pos}")
    if map_device_pos:
        dist = math.hypot(map_device_pos[0] - cx, map_device_pos[1] - cy)
        print(f"Cự ly tới tâm nhân vật: {dist:.1f}px (Cự ly trước đó là ~400px)")
        
        # Di chuột hover vào Map Device và click mở
        print(f"Hover và Click vào Map Device tại ({map_device_pos[0]}, {map_device_pos[1]})...")
        screen_x = cl + map_device_pos[0]
        screen_y = ct + map_device_pos[1]
        win32_input.hover(screen_x, screen_y, delay_after=0.2)
        win32_input.click(screen_x, screen_y, hold_ms=0.08, delay_after=1.5)

        img_opened = capture_window_bitblt(hwnd, client_only=True)
        if img_opened:
            img_opened.save("captures/nav_after_click_map_device.png")
            is_open = vision_ocr.is_atlas_ui_open(img_opened)
            print(f"🎯 KẾT QUẢ: is_atlas_ui_open = {is_open}")
            if is_open:
                print("🎉 THÀNH CÔNG RỰC RỠ! Giao diện Atlas / Map Device đã mở hoàn toàn!")
                return True
    else:
        print("⚠️ Không tìm thấy nhãn Map Device trên màn hình sau di chuyển.")
    return False

if __name__ == "__main__":
    test_nav()
