"""AutoPOE2 - Test Map Tab Tier XV Selection and Inspection.

Mở Stash, chuyển sang Tab Map, click chọn Tier XV để hiển thị danh sách Waystone T15.
"""

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

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

from src.assistant_tool.stash import StashOrchestrator, StashConfig, StashTabType
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 click, ctrl_click, dismiss_modals

def main():
    hwnd = find_poe2_window()
    if not hwnd:
        print("No POE2 window found!")
        return

    ensure_window_focus(hwnd, timeout_ms=800)
    time.sleep(0.5)

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

    print("1. Opening Stash...")
    opened = orchestrator.open_stash(timeout_sec=4.0)
    print(f"Stash opened: {opened}")
    if not opened:
        return

    time.sleep(0.4)
    print("2. Switching to Map Tab...")
    switched = orchestrator.ui_scanner.switch_to_tab(StashTabType.WAYSTONES)
    print(f"Switched: {switched}")

    time.sleep(0.5)
    print("3. Clicking Tier XV button at (678, 325)...")
    click(678, 325, button="left", hold_ms=0.04, delay_after=0.5)

    img_path = capturer.capture_screenshot(event_name="MAP_TAB_TIER15_SELECTED", capture_ram=False)
    print(f"Captured Tier 15 view: {img_path}")

    # Inspect subgrid slots
    img = Image.open(img_path).convert("RGB")
    subgrid_origin_x = 72
    subgrid_origin_y = 490
    subgrid_step_x = 52
    subgrid_step_y = 52

    found_slots = []
    for r in range(9):
        for c in range(8):
            cx = subgrid_origin_x + c * subgrid_step_x
            cy = subgrid_origin_y + r * subgrid_step_y
            # Sample 5x5 average brightness
            total_b = 0
            for dx in range(-5, 6, 2):
                for dy in range(-5, 6, 2):
                    rgb = img.getpixel((cx + dx, cy + dy))
                    total_b += (rgb[0] + rgb[1] + rgb[2]) / 3.0
            avg_b = total_b / 36.0
            if avg_b > 25.0: # Occupied slot
                found_slots.append((c, r, cx, cy, avg_b))

    print(f"Found {len(found_slots)} occupied slots in Tier 15 subgrid:")
    for s in found_slots[:10]:
        print(f"  Slot ({s[0]}, {s[1]}) at ({s[2]}, {s[3]}) avg_brightness={s[4]:.1f}")

    print("\n4. Closing Stash with Spacebar...")
    orchestrator.close_stash()
    time.sleep(0.5)
    print("Done!")

if __name__ == "__main__":
    main()
