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
from src.common.screen_capture import capture_window_bitblt

def run_drop():
    print("=== THỰC HIỆN ĐẶT TRANG BỊ DÍNH CHUỘT VÀO VÙNG TRỐNG TRUNG TÂM TÚI ĐỒ ===")
    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})")

    # 1. Bấm ESC để đóng dialog 'YOU CANNOT DROP THAT ITEM HERE' nếu có
    print("Gửi ESC và Spacebar...")
    win32_input.press_key(0x1B, 0x01, delay_after=0.3)
    win32_input.press_key(0x20, 0x39, delay_after=0.3)

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

    # Chụp ảnh túi đồ trước khi click
    img_before = capture_window_bitblt(hwnd, client_only=True)
    if img_before:
        img_before.save("captures/inv_before_drop.png")

    # 3. Tính toán ô trung tâm vùng trống lớn (Cột 5, Hàng 1)
    # Tọa độ chuẩn 1197x897: x = 974, y = 555
    drop_x = int(round(974 * (cw / 1197.0)))
    drop_y = int(round(555 * (ch / 897.0)))
    print(f"Click thả item vào ô trung tâm vùng trống: ({drop_x}, {drop_y})...")
    win32_input.click(drop_x, drop_y, delay_after=0.8)

    # Chụp ảnh túi đồ sau khi click thả
    img_after = capture_window_bitblt(hwnd, client_only=True)
    if img_after:
        img_after.save("captures/inv_after_drop.png")

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

    # 5. Click test ngoài thế giới
    print("Click test tương tác ngoài thế giới...")
    test_x = int(round(cw * 0.5))
    test_y = int(round(ch * 0.3))
    win32_input.click(test_x, test_y, delay_after=0.8)

    test_img = capture_window_bitblt(hwnd, client_only=True)
    if test_img:
        test_img.save("captures/inv_after_world_click.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("✅ HOÀN TẤT: Con trỏ chuột đã hoàn toàn sạch! Không còn dialog DROP ITEM!")
            return True
    return False

if __name__ == "__main__":
    run_drop()
