"""
AutoPOE2 - Full Launch, Watch & Reconnect Pipeline
Khởi chạy PathOfExile.exe sạch sẽ qua Poe2ClientLauncher,
chờ cửa sổ xuất hiện, sau đó tự động Reconnect và đưa Monk CI vào Shoreline Hideout.
"""

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.assistant_tool.client_launcher import Poe2ClientLauncher
from src.common.win32_window import find_poe2_window
import scripts.reconnect_and_enter_hideout as reconnect_module

def main():
    print("[Pipeline] Bước 1: Khởi chạy POE2 Client...", flush=True)
    launch_ok = Poe2ClientLauncher.launch_client(wait_timeout_sec=60)
    print(f"[Pipeline] Trạng thái launch_client: {launch_ok}", flush=True)

    # Chờ cửa sổ nếu launch_client trả về True nhưng cửa sổ đang render
    hwnd = find_poe2_window()
    if not hwnd:
        print("[Pipeline] Đang chờ thêm cửa sổ POE2 xuất hiện (tối đa 60s)...", flush=True)
        start = time.time()
        while time.time() - start < 60:
            hwnd = find_poe2_window()
            if hwnd:
                print(f"[Pipeline] 🎯 Đã tìm thấy HWND: 0x{hwnd:X} sau {time.time()-start:.1f}s", flush=True)
                break
            time.sleep(1.0)

    if not hwnd:
        print("[Pipeline] ❌ Không tìm thấy cửa sổ POE2 sau khi khởi chạy.", flush=True)
        return False

    print(f"[Pipeline] Bước 2: Cửa sổ POE2 đã sẵn sàng (HWND: 0x{hwnd:X}). Bắt đầu reconnect...", flush=True)
    time.sleep(2.0)

    rc_res = reconnect_module.main(hwnd=hwnd)
    reconnect_ok = bool(rc_res.get("success")) if isinstance(rc_res, dict) else bool(rc_res)
    print(f"[Pipeline] Kết quả Reconnect: {reconnect_ok} | Zone: {rc_res.get('zone') if isinstance(rc_res, dict) else ''}", flush=True)

    if reconnect_ok:
        print("[Pipeline] ✅ Monk CI đã vào Hideout! Bắt đầu Grace Period 10s...", flush=True)
        time.sleep(10.0)
        print("[Pipeline] 🏁 Grace Period kết thúc. Monk CI an toàn tuyệt đối tại Shoreline Hideout.", flush=True)

        if "--daemon" in sys.argv or "--watch" in sys.argv:
            print("[Pipeline] 🛡️ Kích hoạt chế độ Watchdog thường trực (Live Telemetry & Heartbeat)...", flush=True)
            while True:
                time.sleep(15.0)
                if not Poe2ClientLauncher.is_client_running():
                    print("[Watchdog] ⚠️ Client POE2 bị đóng, kích hoạt tự động phục hồi...", flush=True)
                    Poe2ClientLauncher.recover_client_if_crashed()
                    cur_h = find_poe2_window()
                    if cur_h:
                        reconnect_module.main(hwnd=cur_h)
                else:
                    cur_hwnd = find_poe2_window()
                    print(f"[Watchdog Heartbeat] Client POE2 đang hoạt động an toàn tại Hideout (HWND=0x{cur_hwnd:X})", flush=True)

    return reconnect_ok

if __name__ == "__main__":
    ret = main()
    sys.exit(0 if ret else 1)
