"""AutoPOE2 - Quản Lý Cấu Hình & Thẩm Định Trạng Thái Người Dùng (Settings Manager).

Cung cấp các hàm xử lý lưu/nạp cài đặt người dùng, phân tích trạng thái nhân vật
và thẩm định tính hợp lý của chỉ số sinh tồn (Vitals Validation).
"""

from __future__ import annotations

import json
import os
from typing import Any, Dict, Optional, Tuple

from src.assistant_tool import ui_theme as theme


def get_default_settings_path() -> str:
    return os.path.abspath(
        os.path.join(os.path.dirname(__file__), "..", "user_settings.json")
    )


def load_user_settings(filepath: Optional[str] = None) -> Dict[str, Any]:
    """Nạp tệp user_settings.json. Nếu chưa có hoặc lỗi, trả về mặc định."""
    path = filepath or get_default_settings_path()
    if os.path.exists(path):
        try:
            with open(path, "r", encoding="utf-8") as f:
                data = json.load(f)
                if isinstance(data, dict):
                    return data
        except Exception:
            pass
    return {"expected_max_hp": "Auto"}


def save_user_settings(data: Dict[str, Any], filepath: Optional[str] = None) -> bool:
    """Lưu từ điển cài đặt vào user_settings.json."""
    path = filepath or get_default_settings_path()
    try:
        current = load_user_settings(path)
        current.update(data)
        with open(path, "w", encoding="utf-8") as f:
            json.dump(current, f, indent=2)
        return True
    except Exception:
        return False


def get_expected_max_hp_from_str(text: str) -> int:
    """Lấy giá trị expected_max_hp từ chuỗi người dùng nhập:
    - 'Auto', rỗng, '0' -> 0 (Chế độ tự động hoàn toàn).
    - 'ci', 'chaos inoculation' -> 1 (Chaos Inoculation build).
    - Số > 0 -> Giá trị số (Ghi đè thủ công).
    """
    clean = text.strip().lower()
    if clean in ("ci", "chaos inoculation"):
        return 1
    if clean.isdigit():
        val = int(clean)
        if val > 0:
            return val
    return 0


def is_valid_vitals(max_hp: int, current_hp: int = 0) -> bool:
    """Kiểm tra tính hợp lý của Vitals trước khi gửi recalibrate sang C++ Core:
    - Không gửi nếu max_hp < 50 (trừ CI max_hp=1) hoặc max_hp > 30000.
    - Không gửi nếu current_hp > max_hp (khi current_hp > 0).
    - Không gửi nếu max_hp có dạng lặp bất thường (UI markers 778/779, 7793, 77xx).
    """
    if (max_hp < 50 and max_hp != 1) or max_hp > 30000:
        return False
    if current_hp > 0 and current_hp > max_hp:
        return False

    s = str(max_hp)
    if s.startswith(("778", "779", "7793")):
        return False
    if len(s) >= 4 and s.startswith("77") and not s.endswith("00"):
        return False
    if len(s) >= 3 and len(set(s)) == 1:
        return False
    if len(s) == 4 and s[0] == s[1] and s[1] == s[2]:
        return False
    return True


def parse_character_state(flags: int) -> Tuple[str, str, str]:
    """Phân tích movement_flags sang (icon, text, color):
    - Bit 3 (8): 💀 TỬ TRẬN (DEAD)
    - Bit 4 (16): 🛡️ GRACE PERIOD (BẤT TỬ ĐẦU MAP)
    - Bit 1 (2): 🌀 LƯỚT NÉ (ROLLING)
    - Bit 0 (1): 🏃 ĐANG DI CHUYỂN (MOVING)
    - Bit 2 (4): 🧘 ĐỨNG YÊN (IDLE)
    """
    if flags & 8:
        return ("💀", "TỬ TRẬN", theme.c("alert_red"))
    if flags & 16:
        return ("🛡️", "GRACE PERIOD (BẤT TỬ ĐẦU MAP)", theme.c("gold_light"))
    if flags & 2:
        return ("🌀", "LƯỚT NÉ", theme.c("spirit"))
    if flags & 1:
        return ("🏃", "ĐANG DI CHUYỂN", theme.c("info_cyan"))
    if flags & 4:
        return ("🧘", "ĐỨNG YÊN", theme.c("ok"))
    return ("🧘", "ĐỨNG YÊN", theme.c("ok"))
