"""
Cấu hình Hệ thống POE2 Realtime Trading Advisor & Overlay HUD
"""

import os


class Config:
    # 1. Đường dẫn tệp nhật ký game (Client.txt)
    DEFAULT_LOG_PATHS = [
        r"C:\Program Files (x86)\Grinding Gear Games\Path of Exile 2\logs\Client.txt",
        r"C:\Program Files\Grinding Gear Games\Path of Exile 2\logs\Client.txt",
        r"C:\Program Files (x86)\Steam\steamapps\common\Path of Exile 2\logs\Client.txt",
        r"D:\SteamLibrary\steamapps\common\Path of Exile 2\logs\Client.txt",
    ]

    @classmethod
    def get_existing_log_path(cls) -> str:
        found = cls.find_poe2_client_log()
        if found:
            return found
        return cls.DEFAULT_LOG_PATHS[0]

    @classmethod
    def find_poe2_client_log(cls) -> str | None:
        """
        Tìm Client.txt / LatestClient.txt thật của POE2.
        Ưu tiên Client.txt (đủ Generating + SCENE), sau đó LatestClient.txt.
        Trả về None nếu chưa có file — không bịa đường dẫn.
        """
        for p in cls.DEFAULT_LOG_PATHS:
            if os.path.isfile(p):
                return p
        for p in cls.DEFAULT_LOG_PATHS:
            latest = os.path.join(os.path.dirname(p), "LatestClient.txt")
            if os.path.isfile(latest):
                return latest
        discovered = cls._discover_log_from_running_client()
        if discovered:
            return discovered
        return None

    @classmethod
    def _discover_log_from_running_client(cls) -> str | None:
        """Lấy logs\\Client.txt cạnh PathOfExile.exe đang chạy (cài custom / Steam)."""
        try:
            import ctypes
            from ctypes import wintypes

            kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
            TH32CS_SNAPPROCESS = 0x00000002

            class PROCESSENTRY32W(ctypes.Structure):
                _fields_ = [
                    ("dwSize", wintypes.DWORD),
                    ("cntUsage", wintypes.DWORD),
                    ("th32ProcessID", wintypes.DWORD),
                    ("th32DefaultHeapID", ctypes.c_size_t),
                    ("th32ModuleID", wintypes.DWORD),
                    ("cntThreads", wintypes.DWORD),
                    ("th32ParentProcessID", wintypes.DWORD),
                    ("pcPriClassBase", ctypes.c_long),
                    ("dwFlags", wintypes.DWORD),
                    ("szExeFile", wintypes.WCHAR * 260),
                ]

            snap = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
            if snap == wintypes.HANDLE(-1).value:
                return None
            try:
                pe = PROCESSENTRY32W()
                pe.dwSize = ctypes.sizeof(PROCESSENTRY32W)
                if not kernel32.Process32FirstW(snap, ctypes.byref(pe)):
                    return None
                pid = 0
                while True:
                    exe = pe.szExeFile.lower()
                    if exe in ("pathofexile.exe", "pathofexile_x64.exe", "pathofexilesteam.exe"):
                        pid = int(pe.th32ProcessID)
                        break
                    if not kernel32.Process32NextW(snap, ctypes.byref(pe)):
                        break
            finally:
                kernel32.CloseHandle(snap)

            if pid == 0:
                return None

            PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
            hproc = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
            if not hproc:
                return None
            try:
                buf = ctypes.create_unicode_buffer(32768)
                size = wintypes.DWORD(32768)
                QueryFullProcessImageNameW = kernel32.QueryFullProcessImageNameW
                QueryFullProcessImageNameW.argtypes = [
                    wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)
                ]
                QueryFullProcessImageNameW.restype = wintypes.BOOL
                if not QueryFullProcessImageNameW(hproc, 0, buf, ctypes.byref(size)):
                    return None
                exe_path = buf.value
            finally:
                kernel32.CloseHandle(hproc)

            install_dir = os.path.dirname(exe_path)
            client = os.path.join(install_dir, "logs", "Client.txt")
            latest = os.path.join(install_dir, "logs", "LatestClient.txt")
            if os.path.isfile(client):
                return client
            if os.path.isfile(latest):
                return latest
        except Exception:
            return None
        return None

    @classmethod
    def find_poe2_config_path(cls) -> str | None:
        """
        Tìm tệp poe2_production_Config.ini của người chơi.
        Kiểm tra OneDrive, Documents, My Games và AppData.
        """
        candidates = [
            os.path.expanduser(r"~\OneDrive\Documents\My Games\Path of Exile 2\poe2_production_Config.ini"),
            os.path.expanduser(r"~\Documents\My Games\Path of Exile 2\poe2_production_Config.ini"),
            os.path.expanduser(r"~\OneDrive\Documents\My Games\Path of Exile 2\production_Config.ini"),
            os.path.expanduser(r"~\Documents\My Games\Path of Exile 2\production_Config.ini"),
            os.path.expanduser(r"~\AppData\Roaming\Path of Exile 2\poe2_production_Config.ini"),
        ]
        try:
            import ctypes.wintypes
            CSIDL_PERSONAL = 5
            SHGFP_TYPE_CURRENT = 0
            buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
            ctypes.windll.shell32.SHGetFolderPathW(None, CSIDL_PERSONAL, None, SHGFP_TYPE_CURRENT, buf)
            doc_dir = buf.value
            if doc_dir:
                candidates.insert(0, os.path.join(doc_dir, "My Games", "Path of Exile 2", "poe2_production_Config.ini"))
                candidates.insert(1, os.path.join(doc_dir, "My Games", "Path of Exile 2", "production_Config.ini"))
        except Exception:
            pass

        for p in candidates:
            if os.path.isfile(p):
                return p
        return None

    @classmethod
    def detect_poe2_movement_mode(cls) -> tuple[str, str | None]:
        """
        Đọc tệp setting của game và tự động nhận diện chế độ di chuyển:
        Trả về ('wasd', filepath) hoặc ('mouse', filepath) hoặc ('mouse', None nếu không tìm thấy)
        """
        path = cls.find_poe2_config_path()
        if not path:
            return "wasd", None

        try:
            import configparser
            cfg = configparser.ConfigParser(strict=False)
            cfg.read(path, encoding="utf-8-sig")

            user_input_mode = cfg.get("GENERAL", "user_input_mode", fallback="").strip().lower()
            last_kbm = cfg.get("GENERAL", "last_selected_KBM_input_mode", fallback="").strip().lower()

            if user_input_mode == "wasd" or last_kbm == "wasd":
                return "wasd", path

            if cfg.has_section("WASD_ACTION_KEYS"):
                move_up = cfg.get("WASD_ACTION_KEYS", "move_up", fallback="0").strip()
                if move_up == "87" and (user_input_mode == "wasd" or last_kbm == "wasd"):
                    return "wasd", path

            return "wasd", path
        except Exception as e:
            print(f"[Config] Lỗi đọc {path}: {e}")
            return "wasd", path

    # 2. Bảng thuế Vàng (Gold Tax Table) tại Chợ Hối Đoái POE2
    GOLD_TAX_RATES = {
        "BULK_DIVINE": 350,       # Thuế vàng cho mỗi Divine giao dịch hối đoái
        "BULK_CHAOS_BUNDLE": 150, # Thuế vàng cho mỗi lô 100 Chaos
        "PINNACLE_KEY": 450,      # Thuế vàng cho mỗi Chìa khóa Boss Sekhema / Breachstone
        "OMEN": 300,              # Thuế vàng cho mỗi Điềm báo
        "GEM_6LINK": 550,         # Thuế vàng cho mỗi ngọc 6-lỗ hỗ trợ
        "HIGH_RUNE": 250,         # Thuế vàng cho mỗi Cổ tự bậc cao
    }

    # 3. Phân vùng Mùa giải (League Partitions) - Thị trường hoàn toàn độc lập
    DEFAULT_LEAGUE = "Forbidden Rite"
    AVAILABLE_LEAGUES = ["Forbidden Rite", "Standard", "Hardcore Forbidden Rite", "Hardcore"]

    # 3. Giao diện & Màu sắc chủ đạo (SSoT — khớp HUD Core / SHM vitals)
    # HP=đỏ sinh tồn, ES=cyan khiên, Ward=tím, Mana=xanh, Spirit=violet.
    THEME = {
        "bg_dark": "#0a0c10",
        "bg_header": "#0d1117",
        "card_bg": "#131b26",
        "card_bg_alt": "#0f172a",
        "card_border": "#2a3248",
        "accent_gold": "#c89b3c",
        "gold_light": "#fbbf24",
        "profit_green": "#22c55e",
        "ok": "#34d399",
        "ok_hover": "#059669",
        "start": "#10b981",
        "start_hover": "#059669",
        "alert_red": "#ef4444",
        "alert_hover": "#b91c1c",
        "warn": "#f59e0b",
        "info_cyan": "#38bdf8",
        "text_primary": "#f1f5f9",
        "text_muted": "#94a3b8",
        "hp": "#f87171",
        "es": "#38bdf8",
        "ward": "#a78bfa",
        "mana": "#60a5fa",
        "spirit": "#c084fc",
        "log_fg": "#22c55e",
        "log_bg": "#090d13",
        "warn_hover": "#b45309",
        "info": "#0284c7",
        "info_hover": "#0369a1",
        "blue": "#2563eb",
        "blue_hover": "#1d4ed8",
        "bar_track": "#1e293b",
        "muted_btn": "#334155",
        "muted_btn_hover": "#475569",
        "ok_bg": "#064e3b",
        "ok_bg_deep": "#022c22",
        "ok_border": "#10b981",
        "text_on_ok": "#d1fae5",
        "text_on_ok_muted": "#a7f3d0",
        "text_on_ok_bright": "#6ee7b7",
        "spirit_deep": "#1e1b4b",
        "spirit_border": "#6366f1",
        "spirit_hover": "#7c3aed",
        "spirit_fg": "#c7d2fe",
        "inset": "#1e293b",
    }

    # Control Center (không phải Overlay HUD 510x700)
    CONTROL_CENTER_WIDTH = 980
    CONTROL_CENTER_HEIGHT = 680
    CONTROL_CENTER_MIN_WIDTH = 900
    CONTROL_CENTER_MIN_HEIGHT = 600

    # 4. Thiết lập Overlay HUD (Trading Advisor)
    OVERLAY_WIDTH = 510
    OVERLAY_HEIGHT = 700
    DEFAULT_OPACITY = 0.88
    MIN_OPACITY = 0.20
    MAX_OPACITY = 1.00

    # 5. Phím nóng toàn cục (Global Hotkeys)
    HOTKEY_TOGGLE_OVERLAY = "F9"
    HOTKEY_REFRESH_MARKET = "F10"

    # 6. Cấu hình Gemini 3.8 Flash Antigravity AI
    GEMINI_MODEL = os.getenv("GEMINI_MODEL", "gemini-3.8-flash")
    GEMINI_FALLBACK_MODEL = "gemini-3.7-flash"
    GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")

    # 7. Visual Tool độc lập (không gắn F8/Core)
    DEFAULT_ZOOM_MULTIPLIER = 4.0
    DEFAULT_ZOOM_ENABLED = False
    DEFAULT_DISABLE_FOG = False

