"""AutoPOE2 - Live Test Script cho Auto Skill Binder.

Thực hiện gán ngọc kỹ năng ngầm vào ô slot E trên client Path of Exile 2 đang chạy
và chụp ảnh trước/sau để xác minh kết quả trực tiếp mà không chiếm chuột người dùng.
Tuân thủ Rule 1, Rule 5 (100% Dữ liệu Thật), Rule 7 (Non-hijacking controls).
"""

import ctypes
from ctypes import wintypes
import os
import sys
import time
from datetime import datetime
from PIL import Image

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

from src.common.win32_window import find_poe2_window
from src.common.screen_capture import capture_window_bitblt
from src.assistant_tool.skills.skill_constants import (
    ActionBarSlot,
    get_slot_client_pos,
    get_popup_bounding_box,
)
from src.assistant_tool.skills.skill_popup_scanner import SkillPopupScanner
from src.assistant_tool.skills.skill_binder import SkillBinder


def capture_hwnd(hwnd: int) -> Image.Image:
    """Chup anh client area an toan qua common screen_capture."""
    img = capture_window_bitblt(hwnd, client_only=True)
    if img is None:
        raise RuntimeError(f"Khong the chup anh HWND: {hwnd}")
    return img


def main() -> None:
    hwnd = find_poe2_window()
    if not hwnd:
        print("[ERROR] Cannot find Path of Exile 2 window!")
        return

    binder = SkillBinder(hwnd=hwnd)
    cw, ch = binder.get_client_size()
    print(f"[LIVE] Found POE2 HWND: 0x{hwnd:X}, Client Area: {cw}x{ch}")

    # 1. Chup anh truoc khi gan
    time_str = datetime.now().strftime("%Y%m%d_%H%M%S")
    before_img = capture_hwnd(hwnd)
    before_path = f"captures/{time_str}_LIVE_BEFORE_BIND_E.png"
    before_img.save(before_path)
    print(f"[LIVE] Before bind capture saved: {before_path}")

    # Kiem tra toa do slot E
    sx, sy = get_slot_client_pos(ActionBarSlot.SLOT_E, cw, ch)
    print(f"[LIVE] Slot E target position: ({sx}, {sy})")

    # 2. Thuc hien gan Gem Skill tai Row 0, Col 1 vao o E
    print("[LIVE] Executing background bind_gem_skill(Slot E, row=0, col=1)...")
    res = binder.bind_gem_skill(ActionBarSlot.SLOT_E, row=0, col=1, delay_between=0.25)
    print(f"[LIVE] bind_gem_skill result: {res}")

    time.sleep(0.5)

    # 3. Chup anh sau khi gan
    after_img = capture_hwnd(hwnd)
    after_path = f"captures/{time_str}_LIVE_AFTER_BIND_E.png"
    after_img.save(after_path)
    print(f"[LIVE] After bind capture saved: {after_path}")

    # 4. Crop va so sanh icon tai o Slot E
    slot_box = (sx - 22, sy - 22, sx + 22, sy + 22)
    crop_before = before_img.crop(slot_box)
    crop_after = after_img.crop(slot_box)

    crop_before.save(f"captures/{time_str}_SLOT_E_BEFORE.png")
    crop_after.save(f"captures/{time_str}_SLOT_E_AFTER.png")
    print(f"[LIVE] Saved Slot E crops comparison: {time_str}_SLOT_E_BEFORE.png vs AFTER.png")


if __name__ == "__main__":
    main()
