"""
AutoPOE2 - Cửa Sổ Xem Trực Tiếp Màn Hình Game (Live Screen Preview / Mirror)
Cho phép người dùng theo dõi trực tiếp game POE2 đang test ở chế độ ngầm hoặc desktop ảo
mà không làm gián đoạn công việc, không chiếm tiêu điểm chuột.

Tính năng:
- Tự động gắn GUI vào Desktop chính ('Default') để người dùng luôn nhìn thấy.
- Chụp frame buffer của POE2 qua Win32 PrintWindow / GDI Capture (30-60 FPS).
- Cửa sổ Picture-in-Picture có thể tùy chỉnh kích thước, bật/tắt Always-on-Top.
- Phím tắt Space để tạm dừng frame, phím T để ghim cửa sổ lên trên cùng.
"""

import ctypes
import os
import sys
import time
import tkinter as tk
from typing import Optional

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")

# Thêm thư mục gốc vào sys.path để import src.common
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from PIL import Image, ImageTk
from src.common.screen_capture import capture_window_print, capture_rect_bitblt
from src.common.win32_window import find_poe2_window

user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32
GENERIC_ALL = 0x10000000


def attach_thread_to_default_desktop():
    """Bảo đảm thread GUI luôn gắn vào Desktop tương tác chính 'Default'."""
    try:
        hdesk = user32.OpenDesktopW("Default", 0, False, GENERIC_ALL)
        if hdesk:
            user32.SetThreadDesktop(hdesk)
            user32.CloseDesktop(hdesk)
    except Exception as ex:
        print(f"[Preview] Không thể gắn Desktop Default: {ex}")


class Poe2LivePreviewApp:
    def __init__(self, root: tk.Tk):
        self.root = root
        self.root.title("AutoPOE2 - Live Game Preview (Gương Soi Thời Gian Thực)")
        self.root.geometry("800x480")
        self.root.minsize(400, 240)

        # Cấu hình màu sắc
        self.root.configure(bg="#1e1e2e")

        # Trạng thái
        self.is_paused = False
        self.always_on_top = False
        self.fps_counter = 0
        self.last_fps_time = time.time()
        self.current_fps = 0
        self.poe_hwnd: Optional[int] = None

        # Header bar
        self.header = tk.Frame(self.root, bg="#181825", height=36)
        self.header.pack(fill=tk.X, side=tk.TOP)

        self.lbl_status = tk.Label(
            self.header,
            text="Đang tìm kiếm cửa sổ Path of Exile 2...",
            fg="#cdd6f4",
            bg="#181825",
            font=("Segoe UI", 10, "bold")
        )
        self.lbl_status.pack(side=tk.LEFT, padx=12, pady=6)

        self.lbl_fps = tk.Label(
            self.header,
            text="FPS: 0",
            fg="#a6adc8",
            bg="#181825",
            font=("Segoe UI", 9)
        )
        self.lbl_fps.pack(side=tk.RIGHT, padx=12)

        self.btn_top = tk.Button(
            self.header,
            text="📌 Ghim trên cùng: Tắt",
            command=self.toggle_always_on_top,
            bg="#313244",
            fg="#cdd6f4",
            relief=tk.FLAT,
            padx=8,
            font=("Segoe UI", 9)
        )
        self.btn_top.pack(side=tk.RIGHT, padx=6, pady=4)

        # Khung hiển thị hình ảnh
        self.canvas = tk.Canvas(self.root, bg="#11111b", highlightthickness=0)
        self.canvas.pack(fill=tk.BOTH, expand=True)

        self.img_tk = None

        # Bắt phím tắt
        self.root.bind("<space>", lambda e: self.toggle_pause())
        self.root.bind("<t>", lambda e: self.toggle_always_on_top())

        # Bắt đầu chu kỳ cập nhật (30 FPS -> ~33ms)
        self.update_frame()

    def toggle_always_on_top(self):
        self.always_on_top = not self.always_on_top
        self.root.attributes("-topmost", self.always_on_top)
        self.btn_top.config(
            text="📌 Ghim trên cùng: Bật" if self.always_on_top else "📌 Ghim trên cùng: Tắt",
            bg="#89b4fa" if self.always_on_top else "#313244",
            fg="#11111b" if self.always_on_top else "#cdd6f4"
        )

    def toggle_pause(self):
        self.is_paused = not self.is_paused
        status = " (TẠM DỪNG)" if self.is_paused else ""
        self.lbl_status.config(text=f"Trạng thái: {'Đang chạy' if not self.is_paused else 'Tạm dừng'}{status}")

    def find_target_hwnd(self) -> Optional[int]:
        """Tìm HWND game POE2."""
        hwnd = find_poe2_window(["Path of Exile 2", "Path of Exile"])
        if hwnd and user32.IsWindow(hwnd):
            return hwnd
        return None

    def update_frame(self):
        try:
            if not self.is_paused:
                if not self.poe_hwnd or not user32.IsWindow(self.poe_hwnd):
                    self.poe_hwnd = self.find_target_hwnd()

                if self.poe_hwnd:
                    # Chụp frame buffer cửa sổ
                    pil_img = capture_window_print(self.poe_hwnd, render_full_content=True)
                    if pil_img is None:
                        # Fallback capture client area
                        pil_img = capture_rect_bitblt(0, 0, 1920, 1080)

                    if pil_img:
                        cw = self.canvas.winfo_width()
                        ch = self.canvas.winfo_height()
                        if cw > 10 and ch > 10:
                            # Scale giữ tỷ lệ khung hình
                            img_w, img_h = pil_img.size
                            ratio = min(cw / img_w, ch / img_h)
                            new_w = max(1, int(img_w * ratio))
                            new_h = max(1, int(img_h * ratio))

                            resized = pil_img.resize((new_w, new_h), Image.Resampling.BILINEAR)
                            self.img_tk = ImageTk.PhotoImage(resized)

                            self.canvas.delete("all")
                            self.canvas.create_image(
                                cw // 2,
                                ch // 2,
                                anchor=tk.CENTER,
                                image=self.img_tk
                            )

                            self.lbl_status.config(
                                text=f"Đang xem POE2 (HWND: {self.poe_hwnd}) - {img_w}x{img_h}",
                                fg="#a6e3a1"
                            )

                            # Tính toán FPS
                            self.fps_counter += 1
                            now = time.time()
                            if now - self.last_fps_time >= 1.0:
                                self.current_fps = self.fps_counter
                                self.fps_counter = 0
                                self.last_fps_time = now
                                self.lbl_fps.config(text=f"FPS: {self.current_fps}")
                    else:
                        self.lbl_status.config(text="Không thể đọc frame buffer của cửa sổ POE2", fg="#f38ba8")
                else:
                    self.lbl_status.config(text="Đang chờ client POE2 mở (Chưa tìm thấy HWND)...", fg="#f9e2af")
                    self.canvas.delete("all")
                    cw = self.canvas.winfo_width()
                    ch = self.canvas.winfo_height()
                    self.canvas.create_text(
                        cw // 2,
                        ch // 2,
                        text="Chưa tìm thấy cửa sổ game Path of Exile 2.\nHãy khởi chạy game hoặc tool.",
                        fill="#6c7086",
                        font=("Segoe UI", 12, "italic"),
                        justify=tk.CENTER
                    )
        except Exception as e:
            pass

        # Lặp lại sau 33ms (~30 FPS)
        self.root.after(33, self.update_frame)


def main():
    attach_thread_to_default_desktop()
    root = tk.Tk()
    app = Poe2LivePreviewApp(root)
    root.mainloop()


if __name__ == "__main__":
    main()
