"""AutoPOE2 - Inspect Map Tab Live.

Mở Stash, click vào Tab Map để khảo sát giao diện tab Waystones/Maps trong game.
"""

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 dismiss_modals, click

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("Opening Stash...")
    opened = orchestrator.open_stash(timeout_sec=3.0)
    print(f"Stash opened: {opened}")
    if not opened:
        return

    time.sleep(0.5)
    tabs = orchestrator.scan_tabs()
    print(f"Scanned {len(tabs)} tabs.")
    for t in tabs:
        print(f"  Tab #{t.index}: {t.name} ({t.tab_type.value}) at ({t.center_x}, {t.center_y})")

    print("\nSwitching to WAYSTONES / Map Tab...")
    switched = orchestrator.ui_scanner.switch_to_tab(StashTabType.WAYSTONES)
    print(f"Switched: {switched}")

    time.sleep(0.8)
    img_path = capturer.capture_screenshot(event_name="MAP_TAB_VIEW", capture_ram=False)
    print(f"Captured Map Tab screen: {img_path}")

    # Inspect stash slots occupancy
    cur_img = Image.open(img_path).convert("RGB")
    stash_slots = orchestrator.matrix.scan_stash_occupancy(cur_img)
    occupied = [s for s in stash_slots if s.is_occupied]
    print(f"Occupied slots in Map Tab: {len(occupied)}/144")
    for s in occupied[:10]:
        print(f"  Stash slot ({s.col}, {s.row}) at ({s.center_x}, {s.center_y}) avg_rgb={s.avg_rgb:.1f}")

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

if __name__ == "__main__":
    main()
