"""
Script Điều Hướng Hành Lang 3 Chặng từ Vùng Kẹt Về Bệ Đá Map Device (SSoT HideoutNavigator)
Tuân thủ nghiêm ngặt chỉ thị từ Tổng Chỉ Huy.
"""

import os
import sys
import time
from pathlib import Path

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

sys.path.insert(0, str(Path(".").resolve()))

from src.common.win32_window import find_poe2_window, ensure_window_focus, get_client_rect, is_poe2_window_focused
from src.common.win32_input import press_key, send_wasd_direction, hover, click
from src.assistant_tool.screen_capturer import ScreenCapturer
import src.common.vision_ocr as vo
from PIL import Image

def main():
    hwnd = find_poe2_window()
    if not hwnd:
        print("[Corridor Error] Không tìm thấy cửa sổ POE2!", flush=True)
        return False

    print(f"[Corridor] HWND POE2: 0x{hwnd:X}", flush=True)
    ensure_window_focus(hwnd)
    time.sleep(0.3)

    # 1. Giải phóng sạch chatbox và menu tồn đọng bằng ESC và Space
    print("[Corridor] Bước 1: Nhấn ESC và Space giải phóng sạch menu/chatbox...", flush=True)
    press_key(0x1B, 0x01, delay_after=0.3)
    press_key(0x20, 0x39, delay_after=0.3)
    press_key(0x1B, 0x01, delay_after=0.3)

    cl, ct, cw, ch = get_client_rect(hwnd)
    print(f"[Corridor] ClientRect: ({cl}, {ct}, {cw}x{ch})", flush=True)

    capturer = ScreenCapturer(output_dir="captures/pipeline_run")

    def wasd_sender(dx: float, dy: float, dwell: float):
        ensure_window_focus(hwnd)
        ok = send_wasd_direction(dx, dy, dwell_ms=dwell, hwnd=hwnd)
        print(f"  -> WASD ({dx:+.1f}, {dy:+.1f}) dwell={dwell:.1f}s | Success={ok}", flush=True)
        return ok

    # 2. Thực thi 3 chặng theo quy chuẩn HideoutNavigator
    print("\n[Corridor] Bước 2: Thực thi hành lang 3 chặng...", flush=True)

    # Chặng 1: Giữ A (dx=-1.0, dy=1.0, dwell 1.5s) lùi khỏi bờ đá/bụi cây sang trục đường đá
    print("[Corridor] 🚶 Chặng 1: Giữ phím A (dx=-1.0, dy=1.0, dwell 1.5s) lùi khỏi bụi cây...", flush=True)
    wasd_sender(-1.0, 1.0, 1.5)
    time.sleep(0.4)
    cap1 = capturer.capture_screenshot(event_name="CORRIDOR_LEG_1", capture_ram=False)

    # Chặng 2: Giữ S (dx=-1.0, dy=-1.0, dwell 3.5s) xuôi về phía Nam qua Alva/Relic Locker
    print("[Corridor] 🚶 Chặng 2: Giữ phím S (dx=-1.0, dy=-1.0, dwell 3.5s) xuôi Nam qua Alva...", flush=True)
    wasd_sender(-1.0, -1.0, 3.5)
    time.sleep(0.4)
    cap2 = capturer.capture_screenshot(event_name="CORRIDOR_LEG_2", capture_ram=False)

    # Chặng 3: Giữ D / S+D (dx=1.0, dy=-1.0, dwell 2.5s) tiến lên bệ đá Map Device
    print("[Corridor] 🚶 Chặng 3: Giữ phím D (dx=1.0, dy=-1.0, dwell 2.5s) tiến lên bệ đá Map Device...", flush=True)
    wasd_sender(1.0, -1.0, 2.5)
    time.sleep(0.5)
    cap3 = capturer.capture_screenshot(event_name="CORRIDOR_LEG_3", capture_ram=False)

    # 3. Thẩm định quang học sau hành lang
    print("\n[Corridor] Bước 3: Thẩm định quang học hiện trường sau hành lang...", flush=True)
    if cap3 and os.path.exists(cap3):
        img3 = Image.open(cap3)
        res3 = vo.safe_recognize_pil_sync(img3)
        tokens = [l.get("text", "") for l in res3.get("lines", [])]
        print(f"[Corridor] OCR Tokens sau hành lang ({len(tokens)} dòng):", flush=True)
        for t in tokens:
            print(f"   - {t}", flush=True)

        # Kiểm tra Map Device
        md_found = False
        md_pos = None
        for l in res3.get("lines", []):
            txt = l.get("text", "").upper()
            if "MAP" in txt and "DEVICE" in txt:
                words = l.get("words", [])
                if words:
                    min_x = min(w["bounding_rect"]["x"] for w in words)
                    max_x = max(w["bounding_rect"]["x"] + w["bounding_rect"]["width"] for w in words)
                    min_y = min(w["bounding_rect"]["y"] for w in words)
                    max_y = max(w["bounding_rect"]["y"] + w["bounding_rect"]["height"] for w in words)
                    md_pos = (int((min_x + max_x) / 2), int((min_y + max_y) / 2))
                    md_found = True
                    break

        if md_found and md_pos:
            print(f"[Corridor] 🎯 ĐÃ XÁC NHẬN QUANG HỌC MAP DEVICE TẠI: {md_pos}!", flush=True)
            return True, md_pos
        else:
            print("[Corridor] Chưa thấy trực tiếp nhãn MAP DEVICE. Kiểm tra Waypoint / bệ đá...", flush=True)

    return True, None

if __name__ == "__main__":
    main()
