"""AutoPOE2 - Live Verification Script for Stash Management System (Doc 63).

Kiểm thử trực tiếp trên live client game Path of Exile 2:
1. Focus cửa sổ game.
2. Mở Stash tại Hideout bằng click LMB (INV-KEY-NO-F-FOR-INTERACT).
3. Chụp ảnh màn hình lưu vào captures/live_stash_opened.png.
4. Quét và in danh sách các Stash Tabs mà nhân vật BEONGUSI#3653 sở hữu.
5. Quét ma trận các ô trong túi đồ (Inventory).
6. Đóng Stash bằng phím Spacebar.
"""

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

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

try:
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(encoding="utf-8")
except Exception:
    pass

from src.assistant_tool.stash import (
    StashConfig,
    StashUiScanner,
    StashItemMatrix,
    StashOrchestrator,
)
from src.assistant_tool.screen_capturer import ScreenCapturer
from src.common.win32_window import find_poe2_window, ensure_window_focus
from src.common.win32_input import dismiss_modals


def main():
    print("==========================================================")
    print("  AutoPOE2 - LIVE STASH VERIFICATION PROBE (Doc 63)")
    print("==========================================================")

    hwnd = find_poe2_window()
    if not hwnd:
        print("❌ Không tìm thấy cửa sổ game Path of Exile 2!")
        return

    print(f"🎮 Tìm thấy cửa sổ game: HWND={hex(hwnd)}")
    ensure_window_focus(hwnd, timeout_ms=800)
    time.sleep(0.5)

    capturer = ScreenCapturer(output_dir="captures")

    # 1. Chụp ảnh hiện trạng trước khi mở
    img_before_path = capturer.capture_screenshot(event_name="STASH_LIVE_BEFORE", capture_ram=False)
    print(f"📸 Ảnh trước khi mở Stash: {img_before_path}")

    orchestrator = StashOrchestrator(
        screen_w=2560,
        screen_h=1440,
        capture_func=lambda: Image.open(
            capturer.capture_screenshot(event_name="STASH_LIVE_SAMPLE", capture_ram=False)
        ).convert("RGB"),
    )

    # 2. Mở Stash
    print("\n--- BƯỚC 1: Mở Stash tại Hideout (LMB Click tại (830, 804)) ---")
    opened = orchestrator.open_stash(timeout_sec=3.0)
    print(f"👉 Kết quả mở Stash: {'THÀNH CÔNG' if opened else 'THẤT BẠI'}")

    time.sleep(1.0)
    img_open_path = capturer.capture_screenshot(event_name="STASH_LIVE_OPENED", capture_ram=False)
    print(f"📸 Ảnh Stash đã mở: {img_open_path}")

    if not opened:
        print("⚠️ Stash chưa mở thành công, thử kiểm tra ảnh chụp...")
        return

    # 3. Quét danh sách Stash Tabs
    print("\n--- BƯỚC 2: Quét nhận diện các Stash Tabs của nhân vật ---")
    open_img = Image.open(img_open_path).convert("RGB")
    tabs = orchestrator.ui_scanner.scan_stash_tabs(open_img)
    print(f"📋 Tổng số Tab phát hiện: {len(tabs)}")
    for t in tabs:
        print(f"   Tab #{t.index}: Tên='{t.name}' | Loại={t.tab_type.value} | Tâm=({t.center_x}, {t.center_y})")

    # 4. Quét ma trận túi đồ & Đồng bộ RAM Cache
    print("\n--- BƯỚC 3: Quét trạng thái túi đồ (Hybrid RAM + Optical Matrix) ---")
    matrix = orchestrator.matrix
    inv_slots = matrix.scan_inventory_occupancy(open_img)
    occupied = [s for s in inv_slots if s.is_occupied]
    print(f"📦 Số ô có vật phẩm trong túi: {len(occupied)}/60")
    for s in occupied[:5]:
        print(f"   Ô [Cột {s.col}, Hàng {s.row}]: Tâm=({s.center_x}, {s.center_y}), AvgRGB={s.avg_rgb:.1f}")

    # Inspect 3 ô đầu tiên (Hàng 0, Cột 0..2) để cập nhật thuộc tính vào RAM Cache
    print("\n--- BƯỚC 4: Inspect vật phẩm thực địa & Cập nhật RAM Memory Cache ---")
    for c in range(min(3, len(occupied))):
        s = occupied[c]
        rep = matrix.inspect_slot_item_live(s.center_x, s.center_y, col=s.col, row=s.row)
        if rep:
            print(f"   Ô [Cột {s.col}, Hàng {s.row}]: Tên='{rep.item_name}' | Loại={rep.category.value} | Rarity={rep.rarity.value}")

    # Đánh giá điều kiện bảo lưu 5 Waystone
    waystone_count = matrix.memory_reader.get_waystones_count() if matrix.memory_reader else 0
    print(f"\n--- BƯỚC 5: Đánh giá chỉ tiêu Waystone (keep_waystones_count = {orchestrator.config.keep_waystones_count}) ---")
    print(f"🎯 Số lượng Waystone phát hiện trong RAM Cache: {waystone_count}")
    needs_restock = orchestrator.evaluator.should_withdraw_waystone(waystone_count)
    needed_count = orchestrator.config.keep_waystones_count - waystone_count
    print(f"👉 Cần rút bổ sung Waystone từ Stash: {'CÓ (Cần rút thêm ' + str(needed_count) + ' viên)' if needs_restock else 'KHÔNG (Đã đủ)'}")

    if needs_restock:
        print("\n--- BƯỚC 5b: Tự động rút bổ sung Waystone từ Tab Map (Dedicated Map Tab) ---")
        withdrawn = orchestrator.withdraw_waystone_if_needed(open_img, current_waystones_in_bag=waystone_count)
        print(f"👉 Kết quả rút Waystone: {'THÀNH CÔNG' if withdrawn else 'THẤT BẠI'}")

    # 6. Đóng Stash bằng phím Spacebar
    print("\n--- BƯỚC 6: Đóng Stash bằng phím Spacebar (dismiss_modals) ---")
    orchestrator.close_stash()
    time.sleep(0.5)

    img_closed_path = capturer.capture_screenshot(event_name="STASH_LIVE_CLOSED", capture_ram=False)
    print(f"📸 Ảnh sau khi đóng Stash: {img_closed_path}")
    closed_img = Image.open(img_closed_path).convert("RGB")
    is_still_open = orchestrator.ui_scanner.is_stash_open(closed_img)
    print(f"👉 Xác nhận Stash đã đóng hoàn toàn: {'THÀNH CÔNG' if not is_still_open else 'CÒN MỞ'}")
    print("\n==========================================================")
    print(">> HOÀN THÀNH XÁC MINH HYBRID STASH SYSTEM TRÊN CLIENT GAME! <<")
    print("==========================================================")


if __name__ == "__main__":
    main()
