"""
AutoPOE2 Item Tooltip Overlay HUD (Semi-transparent Tkinter Overlay)
Giao diện hiển thị đánh giá vật phẩm POE2 trực quan, hiện đại, độ trễ cực thấp (<1ms).
Đặc tính kỹ thuật:
- Cửa sổ không viền (overrideredirect = True), luôn ghim trên cùng (topmost = True).
- Kiểu cửa sổ Windows Click-through: WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE.
- Tự động căn chỉnh vị trí hiển thị cách con trỏ chuột 15px, tự lật hướng khi sát mép màn hình.
- Header: Tên đồ, Rarity, Badge đánh giá điểm / độ nguy hiểm (Brick / Safe / God Roll).
- Phân mục màu sắc:
  * Xanh Lá: Mod xịn, phần thưởng Map, God Roll
  * Vàng Sáng: Tiềm năng chế đồ, Open Affixes
  * Đỏ: Cảnh báo nguy hiểm, kỵ build, Brick Mods
100% Zero-Crash, an toàn đa luồng (Thread-safe Tkinter dispatch).
"""

from __future__ import annotations

import queue
import sys
import threading
import tkinter as tk
from typing import Optional

import win32con
import win32gui

from src.assistant_tool.item_inspector import (
    AffixType,
    InspectionSeverity,
    ItemCategory,
    ItemInspectionReport,
    ItemRarity,
)


WS_EX_LAYERED = 0x00080000
WS_EX_TRANSPARENT = 0x00000020
WS_EX_NOACTIVATE = 0x08000000


class ItemTooltipOverlay:
    """
    HUD Overlay bán trong suốt hiển thị thông tin đánh giá trang bị POE2.
    """

    BG_COLOR = "#0B0B10"
    BORDER_COLOR = "#4A3820"
    DIVIDER_COLOR = "#382C18"
    TEXT_COLOR = "#E6E6E6"
    GREEN_COLOR = "#2ECC71"
    YELLOW_COLOR = "#F1C40F"
    RED_COLOR = "#FF4D4D"
    NEUTRAL_COLOR = "#8888FF"
    SUB_TEXT_COLOR = "#9E9EB0"

    RARITY_COLORS = {
        ItemRarity.NORMAL: "#DCDCDC",
        ItemRarity.MAGIC: "#8888FF",
        ItemRarity.RARE: "#FFE066",
        ItemRarity.UNIQUE: "#AF6025",
    }

    def __init__(self, root: Optional[tk.Tk] = None):
        self._owns_root = root is None
        # Gắn luồng vào interactive desktop 'default' trước tiên
        from src.assistant_tool.item_hover_watcher import attach_to_default_desktop

        attach_to_default_desktop()

        try:
            if root is not None:
                self.root = root
                self.window = tk.Toplevel(root)
            else:
                self.root = tk.Tk()
                self.window = self.root
        except Exception:
            # Fallback nếu không có DISPLAY hoặc chạy môi trường CI không GUI
            self.root = None
            self.window = None
            self.target_hwnd = None
            self._is_visible = False
            return

        self._is_visible = False
        self._click_through_applied = False
        self._main_thread_id = threading.get_ident()
        self.target_hwnd: Optional[int] = None
        self._event_queue: queue.Queue = queue.Queue()

        # Thiết lập cửa sổ Tkinter
        self.window.withdraw()
        self.window.overrideredirect(True)
        self.window.attributes("-alpha", 0.94)
        self.window.config(bg=self.BG_COLOR)
        self.window.after(20, self._poll_event_queue)

        # Lấy HWND và áp dụng ngay WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE ngay khi tạo cửa sổ
        try:
            self.window.update_idletasks()
            hwnd = self.window.winfo_id()
            parent_hwnd = win32gui.GetParent(hwnd)
            target_hwnd = parent_hwnd if parent_hwnd else hwnd
            self.target_hwnd = target_hwnd

            style = win32gui.GetWindowLong(target_hwnd, win32con.GWL_EXSTYLE)
            win32gui.SetWindowLong(
                target_hwnd,
                win32con.GWL_EXSTYLE,
                style | WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE,
            )
            self._click_through_applied = True
        except Exception:
            pass

        # Tạo container chính với viền kim loại vàng tối #4A3820
        self.main_frame = tk.Frame(
            self.window,
            bg=self.BG_COLOR,
            highlightbackground=self.BORDER_COLOR,
            highlightthickness=1,
            padx=14,
            pady=10,
        )
        self.main_frame.pack(fill=tk.BOTH, expand=True)

        # Header: Tên đồ & Rarity (Căn giữa)
        self.header_frame = tk.Frame(self.main_frame, bg=self.BG_COLOR)
        self.header_frame.pack(fill=tk.X, pady=(0, 2))

        self.badge_label = tk.Label(
            self.header_frame,
            text="",
            font=("Segoe UI", 8, "bold"),
            padx=4,
            pady=1,
            bg=self.BG_COLOR,
        )

        self.name_label = tk.Label(
            self.header_frame,
            text="",
            font=("Segoe UI", 11, "bold"),
            fg=self.TEXT_COLOR,
            bg=self.BG_COLOR,
            anchor="center",
            justify=tk.CENTER,
        )
        self.name_label.pack(fill=tk.X)

        # Subtitle: Phân loại vật phẩm & Item Level (Căn giữa)
        self.sub_label = tk.Label(
            self.header_frame,
            text="",
            font=("Segoe UI", 9),
            fg=self.SUB_TEXT_COLOR,
            bg=self.BG_COLOR,
            anchor="center",
            justify=tk.CENTER,
        )
        self.sub_label.pack(fill=tk.X, pady=(1, 2))

        # Khối danh sách Mods
        self.mods_frame = tk.Frame(self.main_frame, bg=self.BG_COLOR)
        self.mods_frame.pack(fill=tk.BOTH, expand=True)

    def _apply_click_through(self) -> None:
        """Thiết lập kiểu cửa sổ Windows Click-through không cướp focus của game."""
        if self._click_through_applied or self.window is None:
            return

        try:
            if not self.target_hwnd:
                self.window.update_idletasks()
                hwnd = self.window.winfo_id()
                parent_hwnd = win32gui.GetParent(hwnd)
                self.target_hwnd = parent_hwnd if parent_hwnd else hwnd

            target_hwnd = self.target_hwnd
            if target_hwnd:
                style = win32gui.GetWindowLong(target_hwnd, win32con.GWL_EXSTYLE)
                win32gui.SetWindowLong(
                    target_hwnd,
                    win32con.GWL_EXSTYLE,
                    style | WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE,
                )
                self._click_through_applied = True
        except Exception:
            pass

    def _poll_event_queue(self) -> None:
        """Đọc và xử lý sự kiện hiển thị/ẩn từ luồng worker an toàn trên Tkinter thread."""
        try:
            while not self._event_queue.empty():
                action, args = self._event_queue.get_nowait()
                if action == "show":
                    report, sx, sy = args
                    self._show_internal(report, sx, sy)
                elif action == "hide":
                    self._hide_internal()
        except Exception:
            pass
        if self.window is not None:
            try:
                if self.window.winfo_exists():
                    self.window.after(20, self._poll_event_queue)
            except Exception:
                pass

    def show(self, report: ItemInspectionReport, screen_x: int, screen_y: int) -> None:
        """Hiển thị overlay với nội dung báo cáo tại vị trí con trỏ chuột."""
        if self.window is None or report is None:
            return

        # Đảm bảo thực thi an toàn đa luồng trên Tkinter qua hàng đợi (queue)
        if threading.get_ident() != self._main_thread_id:
            self._event_queue.put(("show", (report, screen_x, screen_y)))
        else:
            self._show_internal(report, screen_x, screen_y)

    def _show_internal(self, report: ItemInspectionReport, screen_x: int, screen_y: int) -> None:
        # 1. Cập nhật Header
        rarity_color = self.RARITY_COLORS.get(report.rarity, self.TEXT_COLOR)
        self.name_label.config(text=report.item_name or report.item_class, fg=rarity_color)

        sub_parts = []
        if report.category == ItemCategory.WAYSTONE:
            sub_parts.append(report.base_type or report.item_class)
        else:
            sub_parts.append(f"{report.rarity.value.capitalize()} {report.item_class}")
        if report.item_level > 0:
            sub_parts.append(f"iLvl: {report.item_level}")
        if report.quality > 0:
            sub_parts.append(f"+{report.quality}% Qual")
        sub_text = " | ".join(sub_parts)
        self.sub_label.config(text=sub_text)

        # Badge đánh giá an toàn tinh tế ở góc trên cùng bên phải
        if report.is_brick:
            self.badge_label.config(
                text="⚠️ NGUY HIỂM",
                bg="#3D1010",
                fg=self.RED_COLOR,
            )
            self.badge_label.place(relx=1.0, rely=0.0, anchor="ne")
        else:
            self.badge_label.place_forget()

        # Xóa các dòng mod cũ
        for widget in self.mods_frame.winfo_children():
            widget.destroy()

        # Divider 1: Đường kẻ mỏng tinh tế màu #382C18
        div1 = tk.Frame(self.mods_frame, height=1, bg=self.DIVIDER_COLOR)
        div1.pack(fill=tk.X, pady=(3, 4))

        # Phân tách Implicits / Properties và Explicit Modifiers
        implicits = [m for m in report.ordered_modifiers if m.affix_type == AffixType.IMPLICIT]
        explicits = [m for m in report.ordered_modifiers if m.affix_type != AffixType.IMPLICIT]

        # 1. Implicits / Properties (nếu có, ví dụ Revives Available: 2, Pack Size: +26%)
        if implicits:
            for m in implicits:
                lower = m.text.lower()
                if any(k in lower for k in ["pack size", "quantity", "rarity", "drop chance"]):
                    color = self.GREEN_COLOR
                elif m.severity in [InspectionSeverity.REWARD, InspectionSeverity.GOD_ROLL]:
                    color = self.GREEN_COLOR
                elif m.severity in [InspectionSeverity.BRICK, InspectionSeverity.DANGEROUS]:
                    color = self.RED_COLOR
                else:
                    color = self.SUB_TEXT_COLOR

                m_lbl = tk.Label(
                    self.mods_frame,
                    text=m.text,
                    font=("Segoe UI", 9),
                    fg=color,
                    bg=self.BG_COLOR,
                    anchor="center",
                    justify=tk.CENTER,
                )
                m_lbl.pack(fill=tk.X, pady=(1, 1))

            # Divider giữa Implicits và Explicits
            if explicits:
                div2 = tk.Frame(self.mods_frame, height=1, bg=self.DIVIDER_COLOR)
                div2.pack(fill=tk.X, pady=(3, 4))

        # 2. Explicit Modifiers (Hiển thị từng dòng theo đúng thứ tự report.ordered_modifiers)
        mods_to_display = explicits if implicits else report.ordered_modifiers
        for m in mods_to_display:
            if m.severity in [InspectionSeverity.BRICK, InspectionSeverity.DANGEROUS]:
                color = self.RED_COLOR
            elif m.severity in [InspectionSeverity.REWARD, InspectionSeverity.GOD_ROLL]:
                color = self.GREEN_COLOR
            elif m.severity == InspectionSeverity.CRAFTING:
                color = self.YELLOW_COLOR
            else:
                color = self.NEUTRAL_COLOR

            m_lbl = tk.Label(
                self.mods_frame,
                text=m.text,
                font=("Segoe UI", 9),
                fg=color,
                bg=self.BG_COLOR,
                anchor="center",
                justify=tk.CENTER,
            )
            m_lbl.pack(fill=tk.X, pady=(1, 1))

        # 3. Dòng Open Affixes (nếu có trên trang bị)
        if report.category != ItemCategory.WAYSTONE and (report.open_suffixes > 0 or report.open_prefixes > 0):
            if report.open_suffixes > 0 and report.open_prefixes > 0:
                craft_text = f"— Còn {report.open_prefixes} Open Prefix & {report.open_suffixes} Open Suffix để đập Rune/Exalt —"
            elif report.open_suffixes > 0:
                craft_text = f"— Còn {report.open_suffixes} Open Suffix để đập Rune/Exalt —"
            else:
                craft_text = f"— Còn {report.open_prefixes} Open Prefix để đập Rune/Exalt —"

            craft_lbl = tk.Label(
                self.mods_frame,
                text=craft_text,
                font=("Segoe UI", 8, "italic"),
                fg=self.YELLOW_COLOR,
                bg=self.BG_COLOR,
                anchor="center",
                justify=tk.CENTER,
            )
            craft_lbl.pack(fill=tk.X, pady=(4, 1))

        # Tính toán vị trí và hiển thị chuẩn In-Place (Loại bỏ hoàn toàn -560)
        if not self.window or not self.main_frame:
            return
        self.window.update_idletasks()
        req_w = self.main_frame.winfo_reqwidth() + 10
        req_h = self.main_frame.winfo_reqheight() + 10

        sw = self.window.winfo_screenwidth()
        sh = self.window.winfo_screenheight()

        if screen_x > sw // 2:
            target_x = max(15, screen_x - req_w - 25)
        else:
            target_x = min(sw - req_w - 15, screen_x + 35)

        target_y = max(20, min(screen_y - req_h // 2, sh - req_h - 20))

        self.window.geometry(f"{req_w}x{req_h}+{target_x}+{target_y}")
        if not self.target_hwnd:
            self._apply_click_through()

        if self.target_hwnd:
            win32gui.SetWindowPos(
                self.target_hwnd,
                win32con.HWND_TOPMOST,
                target_x,
                target_y,
                req_w,
                req_h,
                win32con.SWP_NOACTIVATE | win32con.SWP_SHOWWINDOW,
            )
        self._is_visible = True

    def hide(self) -> None:
        """Ẩn overlay tức thì (0ms)."""
        if self.window is None:
            return

        if threading.get_ident() != self._main_thread_id:
            self._event_queue.put(("hide", ()))
        else:
            self._hide_internal()

    def _hide_internal(self) -> None:
        if self._is_visible:
            if self.target_hwnd:
                try:
                    win32gui.ShowWindow(self.target_hwnd, win32con.SW_HIDE)
                except Exception:
                    pass
            elif self.window:
                try:
                    self.window.withdraw()
                except Exception:
                    pass
            self._is_visible = False

    @property
    def is_visible(self) -> bool:
        return self._is_visible

    def mainloop(self) -> None:
        """Chạy vòng lặp giao diện Tkinter."""
        if self.root is not None and self._owns_root:
            self.root.mainloop()


def run_standalone() -> None:
    """Chạy độc lập Auto-Hover Item Inspector HUD."""
    import sys
    getattr(sys.stdout, "reconfigure", lambda **kw: None)(encoding="utf-8", errors="replace")
    getattr(sys.stderr, "reconfigure", lambda **kw: None)(encoding="utf-8", errors="replace")

    from src.assistant_tool.item_hover_watcher import ItemHoverWatcher

    print("=" * 60, flush=True)
    print("  AutoPOE2 Universal Auto-Hover Item Inspector HUD", flush=True)
    print("  Bản quyền 2026 - Thụ động 100% (Zero-Ban Risk)", flush=True)
    print("=" * 60, flush=True)
    print("[*] Khởi tạo giao diện HUD Layered Click-Through...", flush=True)

    overlay = ItemTooltipOverlay()
    if overlay.root is None:
        print("[!] Không thể tạo cửa sổ giao diện Tkinter.", flush=True)
        sys.exit(1)

    def handle_inspect(report: ItemInspectionReport, x: int, y: int) -> None:
        print(
            f"[INSPECTED @ ({x},{y})] {report.item_name} [{report.item_class}] | "
            f"Score: {report.quality_score}/100 | "
            f"🟢 Xanh: {len(report.green_mods)} | 🟡 Vàng: {len(report.yellow_mods)} | 🔴 Đỏ: {len(report.red_mods)}",
            flush=True,
        )
        overlay.show(report, x, y)

    print("[*] Khởi động ItemHoverWatcher (Chu kỳ 40Hz, Dwell 180ms)...", flush=True)
    watcher = ItemHoverWatcher(
        on_item_inspected=handle_inspect,
        on_cursor_moved=overlay.hide,
        dwell_time_ms=180.0,
        enable_focus_interlock=True,
    )
    watcher.start()

    print("[+] ĐÃ SẴN SÀNG! Hãy chuyển vào game Path of Exile 2.", flush=True)
    print("    • Rê chuột dừng yên >= 180ms lên bất kỳ món đồ nào để xem đánh giá.", flush=True)
    print("    • Hoặc nhấn Ctrl+C / Ctrl+Alt+C thủ công để soi tức thì.", flush=True)
    print("    • Di chuyển chuột ra ngoài để tự động ẩn HUD.", flush=True)
    print("[*] Nhấn Ctrl+C trong console này để thoát.", flush=True)
    print("=" * 60, flush=True)

    try:
        overlay.mainloop()
    except KeyboardInterrupt:
        pass
    finally:
        print("[*] Đang dừng watcher...", flush=True)
        watcher.stop()
        print("[+] Đã thoát an toàn.", flush=True)


if __name__ == "__main__":
    run_standalone()

