"""
Feral Corruption & Item Annihilation Engine for FreeExile.
Implements the high-risk, high-reward endgame corruption mechanic that permanently
destroys gear items (Item Sink) and creates godly implicits.
"""

import random
from typing import Optional, List, Tuple
from server.economy.economy_types import CorruptionOutcome, CorruptionResultType
from server.world.primal_stones_crafting import GearItem, Affix, AffixType


class FeralCorruptionEngine:
    GODLY_IMPLICITS = [
        "+1 Cấp Kỹ Năng Ma Võ Toàn Diện",
        "+6% Tỉ Lệ Bạo Kích Tối Thượng",
        "+15% Tốc Độ Thân Pháp & Đòn Đánh Hoang Dã",
        "+12% Kháng Tất Cả Ngũ Hành & +120 Khí Huyết",
        "Tăng 25% Sát Thương Dị Biến Độc & Hỏa",
        "Hồi 3% Khí Huyết Khi Trảm Sát Kẻ Địch"
    ]

    def __init__(self, rng_seed: Optional[int] = None) -> None:
        self._rng = random.Random(rng_seed)
        self.total_corruptions = 0
        self.total_destroyed = 0
        self.total_godly_created = 0

    def corrupt_item(self, item: GearItem, is_already_corrupted: bool = False) -> Tuple[CorruptionOutcome, Optional[GearItem]]:
        """
        Applies Feral Corruption to a gear item.
        Outcomes:
          - 25% GOD_TIER_IMPLICIT: Adds overpowered implicit mod, marks corrupted.
          - 25% PERMANENT_DESTROY: Item is vaporized into bone ash (returns None).
          - 25% CHAOTIC_MUTATION: Affixes are rerolled chaotically, marks corrupted.
          - 25% BRICKED_CORRUPTED: Unchanged, but locked forever.
        """
        if is_already_corrupted:
            return CorruptionOutcome(
                result_type=CorruptionResultType.BRICKED_CORRUPTED,
                success=False,
                message="Trang bị này đã bị tà huyết hủ hóa từ trước, không thể biến dị lần hai!"
            ), item

        self.total_corruptions += 1
        roll = self._rng.random()

        # 1. 25% PERMANENT DESTRUCTION (The Ultimate Item Sink)
        if roll < 0.25:
            self.total_destroyed += 1
            return CorruptionOutcome(
                result_type=CorruptionResultType.PERMANENT_DESTROY,
                success=True,
                item_destroyed=True,
                message="⚠️ Tà khí phản phệ dữ dội! Trang bị đã bị nghiền nát thành tro bụi vĩnh viễn!"
            ), None

        # 2. 25% GOD-TIER IMPLICIT
        elif roll < 0.50:
            self.total_godly_created += 1
            chosen_implicit = self._rng.choice(self.GODLY_IMPLICITS)
            # Add implicit to affixes as special prefix
            new_affix = Affix(
                name=f"[Dị Biến Tà Huyết] {chosen_implicit}",
                affix_type=AffixType.PREFIX,
                stat_key="corrupted_implicit",
                min_val=1, max_val=1, current_val=1
            )
            item.affixes.insert(0, new_affix)
            return CorruptionOutcome(
                result_type=CorruptionResultType.GOD_TIER_IMPLICIT,
                success=True,
                implicit_added=chosen_implicit,
                message=f"🔥 Dị Biến Thành Công! Trang bị thức tỉnh thuộc tính Ngoại Đạo Thần Thánh: {chosen_implicit}!"
            ), item

        # 3. 25% CHAOTIC MUTATION
        elif roll < 0.75:
            # Scramble existing affixes
            for affix in item.affixes:
                affix.current_val = self._rng.randint(affix.min_val, affix.max_val)
            return CorruptionOutcome(
                result_type=CorruptionResultType.CHAOTIC_MUTATION,
                success=True,
                message="🌀 Dòng tà huyết dị biến làm xáo trộn toàn bộ chỉ số của trang bị!"
            ), item

        # 4. 25% BRICKED UNCHANGED
        else:
            return CorruptionOutcome(
                result_type=CorruptionResultType.BRICKED_CORRUPTED,
                success=True,
                message="Trang bị giữ nguyên thuộc tính nhưng bị khóa vĩnh viễn (Corrupted) không thể đẽo gọt thêm."
            ), item
