import os
import sys
import time
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

def clean_cursor():
    print("=== KIỂM TRA & GIẢI PHÓNG CON TRỎ CHUỘT KHỎI ITEM DÍNH ===")
    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

    # Đảm bảo vào Hideout
    cl, ct, cw, ch = get_client_rect(hwnd)
    print(f"HWND: 0x{hwnd:X}, Rect: ({cl}, {ct}, {cw}x{ch})")
    rc = reconnect_module.main(hwnd=hwnd)
    print(f"Reconnect status: {rc.get('success')}")

    ensure_window_focus(hwnd)
    time.sleep(1.0)

    # 1. Bấm ESC và click nút KEEP để đóng dialog confirmation nếu có
    print("Gửi ESC và Spacebar...")
    win32_input.press_key(0x1B, 0x01, delay_after=0.3)
    win32_input.click(cl + int(cw * 0.30), ct + int(ch * 0.54), delay_after=0.3)
    win32_input.press_key(0x20, 0x39, delay_after=0.3)

    # 2. Mở túi đồ (phím 'I')
    print("Mở hành trang bằng phím 'I'...")
    win32_input.press_key(0x49, 0x17, delay_after=0.8)

    # 3. Tính toán ô trống túi đồ an toàn (Cột 2, Hàng 4)
    sx = cw / 2560.0
    sy = ch / 1440.0
    safe_slot_x = int(round(1870 * sx))
    safe_slot_y = int(round(1100 * sy))
    screen_slot_x = cl + safe_slot_x
    screen_slot_y = ct + safe_slot_y
    print(f"Click thả item vào ô túi đồ an toàn: Screen ({screen_slot_x}, {screen_slot_y})...")
    win32_input.click(screen_slot_x, screen_slot_y, delay_after=0.4)
    # Right-click để mặc lại găng tay vào người nếu đó là găng tay Armageddon Grip
    print("Right-click để mặc lại trang bị vào người...")
    win32_input.click(screen_slot_x, screen_slot_y, button="right", delay_after=0.5)

    # 4. Đóng túi đồ
    print("Đóng hành trang bằng phím 'I'...")
    win32_input.press_key(0x49, 0x17, delay_after=0.5)

    # 5. Click test xuống đất để xác nhận không còn popup DROP ITEM
    print("Click test tương tác ngoài thế giới...")
    test_x = cl + int(round(cw * 0.5))
    test_y = ct + int(round(ch * 0.3))
    win32_input.click(test_x, test_y, delay_after=0.8)

    from src.common.screen_capture import capture_window_bitblt
    test_img = capture_window_bitblt(hwnd, client_only=True)
    if test_img:
        test_img.save("captures/clean_cursor_test_result.png")
        res = vision_ocr.safe_recognize_pil_sync(test_img)
        blob = " ".join(l.get("text", "") for l in res.get("lines", [])).upper()
        if any(k in blob for k in ["CANNOT DROP", "DESTROY IT INSTEAD"]):
            print("❌ Vẫn còn dialog DROP ITEM!")
            return False
        else:
            print("✅ XÁC NHẬN: Con trỏ chuột hoàn toàn sạch! Không còn dialog DROP ITEM!")
            return True
    return False

if __name__ == "__main__":
    clean_cursor()
