"""
FreeExile MegaShop Catalog Engine.
Authoritative product registry for Items, Skins, Chests, Coins, and Battle Passes.
Enforces mandatory loot box drop rate transparency and account purchase limits.
"""

from enum import Enum
from typing import Dict, List, Optional
from dataclasses import dataclass, field


class ProductCategory(str, Enum):
    UNKNOWN = "UNKNOWN"
    COINS = "COINS"       # In-game Hard Currency: Huyết Cổ Tệ (Outcast Blood Coins)
    SKINS = "SKINS"       # Visual weapon effects, savage bonehide robes, warbeast skins
    ITEMS = "ITEMS"       # Convenience, respec elixir, bag expansion
    CHESTS = "CHESTS"     # Savage bone caches with transparent probabilistic loot
    PASSES = "PASSES"     # Battle pass, monthly survival passes


@dataclass(slots=True, frozen=True)
class ChestDropProbability:
    item_id: str
    item_name_key: str
    rarity: int                 # 0=Common, 1=Magic, 2=Rare, 3=Unique/Legendary
    drop_chance_percent: float  # Percentage (e.g. 0.05 for 0.05%, 50.0 for 50%)
    is_guaranteed_pity: bool = False


@dataclass(slots=True)
class ShopProduct:
    product_id: str
    name_i18n_key: str
    description_i18n_key: str
    category: ProductCategory
    coin_price: int = 0             # Price in in-game Gold Cores
    base_fiat_usd: float = 0.0      # Direct purchase price in USD
    original_coin_price: int = 0
    discount_percent: int = 0       # 0 to 100
    purchase_limit_per_account: int = 0 # 0 = unlimited
    available_until_ts: int = 0     # 0 = permanent
    badge_label: str = ""           # HOT, NEW, LIMITED, SALE
    chest_drop_rates: List[ChestDropProbability] = field(default_factory=list)

    def calculate_discounted_price(self) -> int:
        if self.discount_percent <= 0:
            return self.coin_price
        discount_factor = (100 - self.discount_percent) / 100.0
        return int(round(self.coin_price * discount_factor))


class MegaShopCatalog:
    """Central Authoritative Catalog for FreeExile Publisher Store."""

    def __init__(self) -> None:
        self._products: Dict[str, ShopProduct] = {}
        self._initialize_default_catalog()

    def _initialize_default_catalog(self) -> None:
        # =========================================================================
        # 1. COIN TIERS (Huyết Cổ Tệ - Outcast Blood Coins)
        # =========================================================================
        self.register_product(ShopProduct(
            product_id="coin_pack_100",
            name_i18n_key="shop.coin.pack_100.name",
            description_i18n_key="shop.coin.pack_100.desc",
            category=ProductCategory.COINS,
            base_fiat_usd=0.99,
            coin_price=100,
            badge_label=""
        ))
        self.register_product(ShopProduct(
            product_id="coin_pack_500",
            name_i18n_key="shop.coin.pack_500.name",
            description_i18n_key="shop.coin.pack_500.desc",
            category=ProductCategory.COINS,
            base_fiat_usd=4.99,
            coin_price=500,
            badge_label="POPULAR"
        ))
        self.register_product(ShopProduct(
            product_id="coin_pack_1000",
            name_i18n_key="shop.coin.pack_1000.name",
            description_i18n_key="shop.coin.pack_1000.desc",
            category=ProductCategory.COINS,
            base_fiat_usd=9.99,
            coin_price=1000,
            badge_label="HOT"
        ))
        self.register_product(ShopProduct(
            product_id="coin_starter_pack_once",
            name_i18n_key="shop.coin.starter_pack.name",
            description_i18n_key="shop.coin.starter_pack.desc",
            category=ProductCategory.COINS,
            coin_price=1000,
            base_fiat_usd=4.99,
            discount_percent=50,
            purchase_limit_per_account=1,
            badge_label="FIRST_BUY_50%_OFF"
        ))
        self.register_product(ShopProduct(
            product_id="coin_pack_2500",
            name_i18n_key="shop.coin.pack_2500.name",
            description_i18n_key="shop.coin.pack_2500.desc",
            category=ProductCategory.COINS,
            base_fiat_usd=24.99,
            coin_price=2500,
            badge_label="BEST_VALUE"
        ))

        # =========================================================================
        # 2. COSMETIC SKINS (Thần Võ Ngoại Trang, Huyễn Ảnh Y, Toạ Kỵ)
        # =========================================================================
        self.register_product(ShopProduct(
            product_id="skin_azure_dragon_blade",
            name_i18n_key="shop.skin.azure_dragon_blade.name",
            description_i18n_key="shop.skin.azure_dragon_blade.desc",
            category=ProductCategory.SKINS,
            coin_price=1800,
            badge_label="EXCLUSIVE"
        ))
        self.register_product(ShopProduct(
            product_id="skin_nether_phoenix_robe",
            name_i18n_key="shop.skin.nether_phoenix_robe.name",
            description_i18n_key="shop.skin.nether_phoenix_robe.desc",
            category=ProductCategory.SKINS,
            coin_price=2400,
            badge_label="LEGENDARY"
        ))
        self.register_product(ShopProduct(
            product_id="skin_spectral_qilin_mount",
            name_i18n_key="shop.skin.spectral_qilin_mount.name",
            description_i18n_key="shop.skin.spectral_qilin_mount.desc",
            category=ProductCategory.SKINS,
            coin_price=3500,
            badge_label="MYTHIC"
        ))

        # =========================================================================
        # 3. UTILITY ITEMS (Vật Phẩm Tiện Ích)
        # =========================================================================
        self.register_product(ShopProduct(
            product_id="item_teleport_scroll_bundle",
            name_i18n_key="shop.item.teleport_bundle.name",
            description_i18n_key="shop.item.teleport_bundle.desc",
            category=ProductCategory.ITEMS,
            coin_price=150,
            badge_label=""
        ))
        self.register_product(ShopProduct(
            product_id="item_inventory_expansion_vault",
            name_i18n_key="shop.item.bag_expansion.name",
            description_i18n_key="shop.item.bag_expansion.desc",
            category=ProductCategory.ITEMS,
            coin_price=600,
            purchase_limit_per_account=5,
            badge_label="ESSENTIAL"
        ))
        self.register_product(ShopProduct(
            product_id="item_premium_merchant_stash_tab",
            name_i18n_key="shop.item.merchant_stash.name",
            description_i18n_key="shop.item.merchant_stash.desc",
            category=ProductCategory.ITEMS,
            coin_price=500,
            purchase_limit_per_account=1,
            badge_label="PREMIUM_TRADE"
        ))
        self.register_product(ShopProduct(
            product_id="item_astral_respec_pill",
            name_i18n_key="shop.item.respec_pill.name",
            description_i18n_key="shop.item.respec_pill.desc",
            category=ProductCategory.ITEMS,
            coin_price=450,
            badge_label=""
        ))
        self.register_product(ShopProduct(
            product_id="item_agent_orb_tier1",
            name_i18n_key="shop.item.agent_orb_tier1.name",
            description_i18n_key="shop.item.agent_orb_tier1.desc",
            category=ProductCategory.ITEMS,
            coin_price=200,
            badge_label="AI_DELEGATE"
        ))
        self.register_product(ShopProduct(
            product_id="item_agent_orb_tier2",
            name_i18n_key="shop.item.agent_orb_tier2.name",
            description_i18n_key="shop.item.agent_orb_tier2.desc",
            category=ProductCategory.ITEMS,
            coin_price=600,
            badge_label="POPULAR"
        ))
        self.register_product(ShopProduct(
            product_id="item_agent_orb_tier3",
            name_i18n_key="shop.item.agent_orb_tier3.name",
            description_i18n_key="shop.item.agent_orb_tier3.desc",
            category=ProductCategory.ITEMS,
            coin_price=1500,
            badge_label="BEST_VALUE"
        ))

        # =========================================================================
        # 4. MYSTERY CHESTS (Cổ Man Cốt Hạp với tỉ lệ 100% minh bạch)
        # =========================================================================
        self.register_product(ShopProduct(
            product_id="chest_celestial_fortune",
            name_i18n_key="shop.chest.celestial_fortune.name",
            description_i18n_key="shop.chest.celestial_fortune.desc",
            category=ProductCategory.CHESTS,
            coin_price=200,
            badge_label="GACHA",
            chest_drop_rates=[
                ChestDropProbability("loot_manh_xuong_co", "curr.bone_fragment.name", rarity=0, drop_chance_percent=45.0),
                ChestDropProbability("loot_da_lua_hoang_da", "curr.savage_flint.name", rarity=1, drop_chance_percent=30.0),
                ChestDropProbability("loot_huyet_hon_thach", "curr.primal_bloodstone.name", rarity=2, drop_chance_percent=20.0),
                ChestDropProbability("loot_co_cot_an", "curr.ancient_bone_brand.name", rarity=2, drop_chance_percent=4.5),
                ChestDropProbability("loot_huyet_anh_co_kinh", "curr.savage_blood_mirror.name", rarity=3, drop_chance_percent=0.5, is_guaranteed_pity=True),
            ]
        ))
        self.register_product(ShopProduct(
            product_id="chest_abyssal_sovereign",
            name_i18n_key="shop.chest.abyssal_sovereign.name",
            description_i18n_key="shop.chest.abyssal_sovereign.desc",
            category=ProductCategory.CHESTS,
            coin_price=500,
            badge_label="LIMITED",
            chest_drop_rates=[
                ChestDropProbability("loot_u_minh_cot_dinh", "curr.wraithbone_spike.name", rarity=2, drop_chance_percent=55.0),
                ChestDropProbability("loot_co_cot_an_x5", "curr.ancient_bone_brand.name", rarity=2, drop_chance_percent=35.0),
                ChestDropProbability("loot_unique_skin_aura", "shop.skin.abyssal_aura.name", rarity=3, drop_chance_percent=8.5),
                ChestDropProbability("loot_huyet_anh_co_kinh_pure", "curr.savage_blood_mirror.name", rarity=3, drop_chance_percent=1.5, is_guaranteed_pity=True),
            ]
        ))

        # =========================================================================
        # 5. PASSES & SUBSCRIPTIONS (Thần Ma Lệnh, Thẻ Tháng)
        # =========================================================================
        self.register_product(ShopProduct(
            product_id="pass_monthly_astral_blessing",
            name_i18n_key="shop.pass.monthly_blessing.name",
            description_i18n_key="shop.pass.monthly_blessing.desc",
            category=ProductCategory.PASSES,
            base_fiat_usd=4.99,
            coin_price=0,
            badge_label="30_DAYS"
        ))
        self.register_product(ShopProduct(
            product_id="pass_battle_than_ma_lenh",
            name_i18n_key="shop.pass.battle_pass_s1.name",
            description_i18n_key="shop.pass.battle_pass_s1.desc",
            category=ProductCategory.PASSES,
            base_fiat_usd=9.99,
            coin_price=1000,
            badge_label="SEASON_1"
        ))

    def register_product(self, product: ShopProduct) -> None:
        self._products[product.product_id] = product

    def get_product(self, product_id: str) -> Optional[ShopProduct]:
        return self._products.get(product_id)

    def get_all_products(self) -> List[ShopProduct]:
        return list(self._products.values())

    def get_products_by_category(self, category: ProductCategory) -> List[ShopProduct]:
        return [p for p in self._products.values() if p.category == category]
