"""
Item Crafting Types, Enums and Data Models for FreeExile.
Strictly decoupled from crafting logic and catalog definitions.
Follows PoE2 itemization with Grimdark Savage Primal Exile flavor.
"""

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Tuple, Set


class ItemSlot(Enum):
    """Canonical equipment slots in FreeExile."""
    WEAPON_1H = "WEAPON_1H"         # Đoản Đao, Cốt Kiếm, Tà Phủ 1 tay
    WEAPON_2H = "WEAPON_2H"         # Cự Đao, Đại Thương, Ma Cung 2 tay
    BODY_ARMOUR = "BODY_ARMOUR"     # Hắc Bì Giáp, Cốt Giáp, Đạo Bào
    HELMET = "HELMET"               # Cốt Khôi, Đầu Lâu Dị Biến
    GLOVES = "GLOVES"               # Cốt Trảo, Thiết Hộ Uyển
    BOOTS = "BOOTS"                 # Cốt Hài, Huyễn Ảnh Hài
    SHIELD = "SHIELD"               # Huyết Thuẫn, Cốt Bài
    RING = "RING"                   # Ma Cốt Giới Chỉ
    AMULET = "AMULET"               # Huyết Tủy Hộ Phù
    BELT = "BELT"                   # Xích Cốt Đai, Hắc Bì Yêu Đái


class ItemRarity(Enum):
    """Item rarity categories."""
    NORMAL = "NORMAL"               # Phế Phẩm (Trắng - 0 mod)
    MAGIC = "MAGIC"                 # Man Tộc (Lam - 1-2 mods)
    RARE = "RARE"                   # Tà Binh (Hoàng Kim - 3-6 mods)
    UNIQUE = "UNIQUE"               # Thần Binh Độc Bản (Cam - Lore fixed)


class AffixType(Enum):
    """Categorization of item modifiers."""
    PREFIX = "PREFIX"               # Tiền Tố (Công, Sinh Lực, Phòng Ngự Gốc)
    SUFFIX = "SUFFIX"               # Hậu Tố (Tốc Độ, Bạo Kích, Kháng Tính, Chỉ Số)
    IMPLICIT = "IMPLICIT"           # Dòng Cố Định Phôi Đồ
    CORRUPTED = "CORRUPTED"         # Dòng Biến Dị Tà Huyết


class DownsidePenaltyType(Enum):
    """Types of severe penalties attached to overpowered trade-off affixes."""
    LIFE_DEGEN_PCT = "LIFE_DEGEN_PCT"                   # Mất % HP mỗi giây khi giao chiến
    REDUCE_MAX_RES_CAP = "REDUCE_MAX_RES_CAP"           # Giảm trần kháng tối đa
    CANNOT_EVADE_OR_DASH = "CANNOT_EVADE_OR_DASH"       # Không thể dùng thân pháp lướt né
    BLIND_AILMENT = "BLIND_AILMENT"                     # Dính trạng thái mù (giảm tầm nhìn & né)
    SKILL_DRAIN_CURRENT_LIFE = "SKILL_DRAIN_CURRENT_LIFE" # Tiêu hao % máu hiện tại khi dùng skill
    TAKE_INCREASED_DMG = "TAKE_INCREASED_DMG"           # Nhận thêm % sát thương từ kẻ địch
    CANNOT_REGEN_OR_LEECH = "CANNOT_REGEN_OR_LEECH"     # Không thể hồi phục hay hút máu


class PrimalCurrencyType(Enum):
    """
    Savage Barter Currencies & Endgame Materials.
    100% consumable, zero gold fiat.
    """
    # Quality & Base Preparation Currency
    HAC_THACH_MAI_NHAN = "HAC_THACH_MAI_NHAN"           # Whetstone: Quality Vũ Khí (+1% to 20%)
    COT_GIAP_THAO_THIET = "COT_GIAP_THAO_THIET"         # Armour Scrap: Quality Giáp Ngực/Mũ/Găng/Giày (+1% to 20%)
    BAO_MA_THACH = "BAO_MA_THACH"                       # Alteration: Reroll Magic item (1-2 mods)
    TRO_XUONG_TAY_UE = "TRO_XUONG_TAY_UE"               # Scour: Remove all mods, reset to Normal

    # Standard Primal Currency
    HAC_SO_THACH = "HAC_SO_THACH"                       # Transmutation: Normal -> Magic (1-2 mods)
    UAN_MA_THACH = "UAN_MA_THACH"                       # Augmentation: Magic 1 mod -> 2 mods
    CO_COT_AN = "CO_COT_AN"                             # Regal: Magic -> Rare (+1 mod)
    HUYET_HON_THACH = "HUYET_HON_THACH"                 # Chaos: Reroll Rare (3-6 mods)
    U_MINH_COT_DINH = "U_MINH_COT_DINH"                 # Exalted: Slam 1 mod to Rare (max 6)
    COT_DAO_TUOC_DOAT = "COT_DAO_TUOC_DOAT"             # Annulment: Remove 1 random mod
    TINH_HOA_HUYET_THACH = "TINH_HOA_HUYET_THACH"       # Divine: Reroll mod values within tier
    TA_HUYET_DI_BIEN_THACH = "TA_HUYET_DI_BIEN_THACH"   # Vaal / Corruption (25% Annihilation)
    HUYET_ANH_CO_KINH = "HUYET_ANH_CO_KINH"             # Mirror of Kalandra (Duplicate immutable)

    # Pinnacle Boss & Endgame Map Materials
    TINH_HUYET_VIEM_QUY = "TINH_HUYET_VIEM_QUY"         # Flame Demon Core: Guaranteed T1 Fire Mod
    TAN_HON_XA_QUAI = "TAN_HON_XA_QUAI"                 # Abyssal Serpent Soul: Guaranteed T1 Speed/Dodge
    COT_TUY_HAC_LONG = "COT_TUY_HAC_LONG"               # Black Dragon Marrow: Fracture 1 random mod
    DIEM_BAO_HOANG_VU = "DIEM_BAO_HOANG_VU"             # Omen of Fortune: Guarantees next slam is T1


@dataclass(slots=True)
class AffixDefinition:
    """Template definition of an affix tier."""
    mod_id: str
    mod_name: str
    affix_type: AffixType
    tier: int                                           # 1 = Best (God-tier), 5 = Lowest
    required_ilvl: int                                  # Item level requirement (e.g. 85 for T1)
    min_val: float
    max_val: float
    weight: int                                         # Roll weight (lower = rarer)
    allowed_slots: Set[ItemSlot]                        # Allowed equipment slots
    is_downside_affix: bool = False
    downside_type: Optional[DownsidePenaltyType] = None
    downside_val: float = 0.0
    downside_desc: str = ""


@dataclass(slots=True)
class AffixMod:
    """Instance of an affix applied to an item."""
    mod_id: str
    mod_name: str
    mod_type: AffixType
    tier: int
    value: float
    tier_min: float = 0.0                               # Minimum boundary of this tier
    tier_max: float = 0.0                               # Maximum boundary of this tier
    is_fractured: bool = False                          # Locked permanently
    is_downside: bool = False
    downside_type: Optional[DownsidePenaltyType] = None
    downside_val: float = 0.0
    downside_desc: str = ""


@dataclass(slots=True)
class CraftingItem:
    """Server-authoritative item representation."""
    item_uuid: str
    base_name: str
    item_level: int
    slot: ItemSlot = ItemSlot.WEAPON_1H
    rarity: ItemRarity = ItemRarity.NORMAL
    quality: int = 0                                    # Độ hoàn thiện / sắc bén 0-20%
    prefixes: List[AffixMod] = field(default_factory=list)
    suffixes: List[AffixMod] = field(default_factory=list)
    implicits: List[AffixMod] = field(default_factory=list)
    is_corrupted: bool = False
    is_mirrored: bool = False
    is_destroyed: bool = False                          # Tro bụi do Annihilation

    @property
    def total_affixes_count(self) -> int:
        return len(self.prefixes) + len(self.suffixes)


@dataclass(slots=True)
class CraftingResult:
    """Result payload of a crafting action."""
    success: bool
    status_code: str
    message: str
    item: CraftingItem
    consumed_currency: str
    gold_fee_consumed: int = 0
