"""AutoPOE2 - Stash Evaluator & Routing Engine (Doc 63 / SSoT 2026).

Bộ đánh giá nghiệp vụ và phân luồng vật phẩm:
- Quyết định hành động Cất (DEPOSIT), Giữ lại (KEEP) hay Bỏ qua (IGNORE) cho từng món đồ.
- Định tuyến chính xác loại Tab đích (Currency -> Tab Currency, Waystone -> Tab Waystone...).
- Xác định điều kiện rút vật phẩm bổ sung (Restock Waystone) khi túi đồ thiếu thốn.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple

from src.assistant_tool.item_inspector import (
    ItemCategory,
    ItemInspectionReport,
    ItemRarity,
)
from src.assistant_tool.stash.stash_constants import (
    StashAction,
    StashConfig,
    StashTabType,
)


@dataclass
class ItemRoutingDecision:
    """Quyết định điều phối cho một vật phẩm."""
    action: StashAction
    target_tab_type: StashTabType
    reason: str
    item_category: ItemCategory = ItemCategory.OTHER
    item_name: str = ""


class StashEvaluator:
    """Bộ đánh giá và phân luồng cất/rút đồ Stash."""

    def __init__(self, config: Optional[StashConfig] = None):
        self.config = config or StashConfig()

    def evaluate_inventory_item(
        self,
        item_report: Optional[ItemInspectionReport],
        current_waystones_kept: int = 0,
    ) -> ItemRoutingDecision:
        """
        Đánh giá một vật phẩm trong túi đồ để quyết định CẤT hay GIỮ.
        
        Args:
            item_report: Báo cáo thuộc tính vật phẩm từ UniversalItemParser.
            current_waystones_kept: Số lượng Waystone đã được giữ lại trong túi đợt này.
        """
        if item_report is None:
            # Nếu không đọc được chi tiết tooltip (hoặc chưa inspect), mặc định theo affinity hoặc cất an toàn
            return ItemRoutingDecision(
                action=StashAction.DEPOSIT if self.config.use_stash_affinity else StashAction.KEEP,
                target_tab_type=StashTabType.DUMP,
                reason="Uninspected item - fallback deposit via affinity" if self.config.use_stash_affinity else "Uninspected - keep safe",
            )

        cat = item_report.category
        name = item_report.item_name or item_report.base_type

        # 1. Cuộn Giám Định (Scroll of Wisdom) -> Luôn giữ lại để dùng
        if "Scroll of Wisdom" in name or "Wisdom" in name:
            return ItemRoutingDecision(
                action=StashAction.KEEP,
                target_tab_type=StashTabType.CURRENCY,
                reason="Giữ lại Scroll of Wisdom để giám định vật phẩm dã chiến",
                item_category=cat,
                item_name=name,
            )

        # 2. Waystones & Precursor Tablets
        if cat == ItemCategory.WAYSTONE or "Waystone" in name or "Tablet" in name:
            # Kiểm tra xem đã đủ số lượng Waystone cần giữ lại trong túi chưa
            if current_waystones_kept < self.config.keep_waystones_count:
                return ItemRoutingDecision(
                    action=StashAction.KEEP,
                    target_tab_type=StashTabType.WAYSTONES,
                    reason=f"Giữ lại Waystone ({current_waystones_kept + 1}/{self.config.keep_waystones_count}) cho map tiếp theo",
                    item_category=cat,
                    item_name=name,
                )
            else:
                return ItemRoutingDecision(
                    action=StashAction.DEPOSIT,
                    target_tab_type=StashTabType.WAYSTONES,
                    reason=f"Cất Waystone dư thừa vào Tab Waystones",
                    item_category=cat,
                    item_name=name,
                )

        # 3. Currency (Tiền tệ, Runes, Soul Cores, Shards)
        if cat == ItemCategory.CURRENCY or "Orb" in name or "Rune" in name or "Core" in name:
            if self.config.deposit_currency:
                return ItemRoutingDecision(
                    action=StashAction.DEPOSIT,
                    target_tab_type=StashTabType.CURRENCY,
                    reason="Cất tiền tệ và nguyên liệu vào Tab Currency",
                    item_category=cat,
                    item_name=name,
                )
            return ItemRoutingDecision(
                action=StashAction.KEEP,
                target_tab_type=StashTabType.CURRENCY,
                reason="Tùy chọn cất tiền tệ đang tắt",
                item_category=cat,
                item_name=name,
            )

        # 4. Gems (Uncut Skill/Support/Spirit Gems)
        if "Gem" in name or "Uncut" in name:
            if self.config.deposit_gems:
                return ItemRoutingDecision(
                    action=StashAction.DEPOSIT,
                    target_tab_type=StashTabType.GEMS,
                    reason="Cất Uncut Gems vào Tab Gems",
                    item_category=cat,
                    item_name=name,
                )
            return ItemRoutingDecision(
                action=StashAction.KEEP,
                target_tab_type=StashTabType.GEMS,
                reason="Tùy chọn cất Gem đang tắt",
                item_category=cat,
                item_name=name,
            )

        # 5. Trang bị (Weapons, Armours, Accessories, Shields)
        gear_categories = {
            ItemCategory.WEAPON,
            ItemCategory.BODY_ARMOUR,
            ItemCategory.HELMET,
            ItemCategory.BOOTS,
            ItemCategory.GLOVES,
            ItemCategory.SHIELD,
            ItemCategory.QUIVER,
            ItemCategory.RING,
            ItemCategory.AMULET,
            ItemCategory.BELT,
            ItemCategory.JEWEL,
        }
        if cat in gear_categories:
            if self.config.deposit_gear:
                return ItemRoutingDecision(
                    action=StashAction.DEPOSIT,
                    target_tab_type=StashTabType.DUMP,
                    reason="Cất trang bị vào Tab Dump chờ lọc hoặc trade",
                    item_category=cat,
                    item_name=name,
                )
            return ItemRoutingDecision(
                action=StashAction.KEEP,
                target_tab_type=StashTabType.DUMP,
                reason="Tùy chọn cất trang bị đang tắt",
                item_category=cat,
                item_name=name,
            )

        # 6. Bùa ngọc Charms & Bình Flask
        if cat in (ItemCategory.CHARM, ItemCategory.FLASK):
            return ItemRoutingDecision(
                action=StashAction.DEPOSIT,
                target_tab_type=StashTabType.FLASKS,
                reason="Cất Charms và Bình dược vào hòm",
                item_category=cat,
                item_name=name,
            )

        # Mặc định cất nếu có Stash Affinity, hoặc giữ lại nếu chưa rõ
        return ItemRoutingDecision(
            action=StashAction.DEPOSIT if self.config.use_stash_affinity else StashAction.KEEP,
            target_tab_type=StashTabType.DUMP,
            reason="Vật phẩm thông thường khác",
            item_category=cat,
            item_name=name,
        )

    def should_withdraw_waystone(self, current_inventory_waystone_count: int) -> bool:
        """Kiểm tra xem có cần rút Waystone từ Stash bổ sung cho túi đồ không."""
        return current_inventory_waystone_count < self.config.keep_waystones_count
