"""
AutoPOE2 - Watch and Reconnect Runner
Giám sát tiến trình POE2 PID 47288 cho đến khi cửa sổ game xuất hiện,
sau đó lập tức kích hoạt reconnect_and_enter_hideout.py và ghi nhận kết quả.
"""

import sys
import time
import os
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(__file__).resolve().parent.parent))

from src.common.win32_window import find_poe2_window
import scripts.reconnect_and_enter_hideout as reconnect_module

def main():
    print("[WatchAndReconnect] Bắt đầu giám sát cửa sổ POE2...", flush=True)
    start_time = time.time()
    max_wait_seconds = 300 # 5 phút
    found_hwnd = None

    while time.time() - start_time < max_wait_seconds:
        hwnd = find_poe2_window()
        if hwnd:
            found_hwnd = hwnd
            elapsed = time.time() - start_time
            print(f"[WatchAndReconnect] 🎯 CỬA SỔ POE2 ĐÃ XUẤT HIỆN! HWND=0x{hwnd:X} (sau {elapsed:.1f}s)", flush=True)
            break
        time.sleep(1.0)

    if not found_hwnd:
        print(f"[WatchAndReconnect] ❌ Hết thời gian chờ {max_wait_seconds}s mà chưa thấy cửa sổ POE2.", flush=True)
        return False

    # Chờ thêm 2 giây để cửa sổ render frame đầu tiên ổn định
    time.sleep(2.0)

    print("[WatchAndReconnect] Kích hoạt reconnect_and_enter_hideout.py...", flush=True)
    success = reconnect_module.main()
    print(f"[WatchAndReconnect] Kết quả reconnect: {success}", flush=True)

    if success:
        print("[WatchAndReconnect] ✅ Đã đưa Monk CI vào Hideout an toàn! Kích hoạt Grace Period 10s...", flush=True)
        time.sleep(10.0)
        print("[WatchAndReconnect] Grace Period kết thúc. Nhân vật đã ổn định tại Hideout.", flush=True)

    return success

if __name__ == "__main__":
    ret = main()
    sys.exit(0 if ret else 1)
