import os
import sys
import time
import numpy as np
from PIL import Image

sys.path.insert(0, ".")

from src.assistant_tool.client_launcher import Poe2ClientLauncher
from src.common.win32_window import find_poe2_window, ensure_window_focus, is_poe2_window_focused
import src.common.win32_input as win32_input
from src.common.screen_capture import capture_window_bitblt
import scripts.reconnect_and_enter_hideout as reconnect_module

def main():
    print("=== DEBUG WASD PULSE & FOCUS SENTINEL ===", flush=True)
    hwnd = find_poe2_window()
    if not hwnd:
        print("Khởi chạy client POE2...", flush=True)
        Poe2ClientLauncher.launch_client(wait_timeout_sec=90)
        for _ in range(90):
            hwnd = find_poe2_window()
            if hwnd:
                break
            time.sleep(1.0)

    rc = reconnect_module.main(hwnd=hwnd)
    print(f"Reconnect status: {rc.get('success')}", flush=True)

    time.sleep(2.0)
    focused = is_poe2_window_focused(hwnd)
    phys_allowed = win32_input._is_physical_allowed(hwnd=hwnd)
    print(f"Game HWND: 0x{hwnd:X}, Focused: {focused}, PhysicalAllowed: {phys_allowed}", flush=True)

    # Chụp ảnh trước khi di chuyển
    img1 = capture_window_bitblt(hwnd, client_only=True)

    print("Thử bơm phím A (sang Tây) trong 1.5s...", flush=True)
    t0 = time.time()
    res = win32_input.send_wasd_direction(-1.0, 1.0, dwell_ms=1.5, hwnd=hwnd)
    elapsed = time.time() - t0
    print(f"send_wasd_direction result: {res}, Thực tế chạy mất: {elapsed:.3f}s", flush=True)

    time.sleep(0.5)
    img2 = capture_window_bitblt(hwnd, client_only=True)

    if img1 and img2:
        b = np.array(img1).astype(float)
        a = np.array(img2).astype(float)
        diff = np.abs(b - a)
        p_changed = (diff > 30).sum()
        print(f"Mean diff: {diff.mean():.2f}, Pixels > 30: {p_changed}", flush=True)
        if p_changed > 10000:
            print("🎉 THÀNH CÔNG: Nhân vật ĐÃ DI CHUYỂN RÕ RỆT!", flush=True)
        else:
            print("⚠️ CẢNH BÁO: Nhân vật KHÔNG DI CHUYỂN!", flush=True)

if __name__ == "__main__":
    main()
