"""
Bộ Thẩm Định Đa Chiều 'What Is Better' (Pareto Decision & Comparison Engine)
Chuyên trách so sánh, đánh giá và trả lời dứt khoát câu hỏi: "Cái nào tốt hơn và vì sao?"
áp dụng cho Trang bị (Gear), Kỹ năng (Skills) và Chiến lược Kinh tế (Economy).
"""

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


@dataclass
class ItemStats:
    name: str
    slot: str
    item_level: int = 1
    rarity: str = "Rare"
    flat_phys: float = 0.0
    flat_cold: float = 0.0
    flat_fire: float = 0.0
    flat_lightning: float = 0.0
    attack_speed_pct: float = 0.0
    crit_multiplier_pct: float = 0.0
    max_life: int = 0
    fire_res: int = 0
    cold_res: int = 0
    lightning_res: int = 0
    chaos_res: int = 0
    spell_suppression_pct: int = 0
    movement_speed_pct: int = 0
    estimated_trade_value_chaos: float = 0.0


@dataclass
class ItemComparisonResult:
    winner: str
    decision: str
    utility_delta: float
    dps_delta_pct: float
    ehp_delta_pct: float
    resist_impact_warning: Optional[str]
    headline_verdict: str
    detailed_reasoning: str
    salvage_or_trade_advice: str


class WhatIsBetterEvaluator:
    """
    Bộ Thẩm Định Đa Chiều Quyết Định 'What Is Better'.
    """

    def __init__(self, target_build_name: str = "Martial Artist (Hollow Form Whirling Assault)"):
        self.target_build_name = target_build_name
        self.weight_dps = 1.0
        self.weight_ehp = 1.2
        self.weight_speed = 0.8

    def compare_items(
        self,
        current_item: ItemStats,
        candidate_item: ItemStats,
        player_current_resists: Optional[Dict[str, int]] = None
    ) -> ItemComparisonResult:
        curr_flat = (current_item.flat_phys + current_item.flat_cold * 1.3 +
                     current_item.flat_fire + current_item.flat_lightning)
        cand_flat = (candidate_item.flat_phys + candidate_item.flat_cold * 1.3 +
                     candidate_item.flat_fire + candidate_item.flat_lightning)

        curr_dps_score = curr_flat * (1.0 + current_item.attack_speed_pct / 100.0) * (1.0 + current_item.crit_multiplier_pct / 200.0)
        cand_dps_score = cand_flat * (1.0 + candidate_item.attack_speed_pct / 100.0) * (1.0 + candidate_item.crit_multiplier_pct / 200.0)

        base_dps = max(1.0, curr_dps_score)
        dps_delta_pct = round(((cand_dps_score - curr_dps_score) / base_dps) * 100.0, 1)

        curr_res_sum = current_item.fire_res + current_item.cold_res + current_item.lightning_res + current_item.chaos_res * 1.5
        cand_res_sum = candidate_item.fire_res + candidate_item.cold_res + candidate_item.lightning_res + candidate_item.chaos_res * 1.5

        curr_ehp_score = current_item.max_life * 1.5 + curr_res_sum * 2.0 + current_item.spell_suppression_pct * 3.0
        cand_ehp_score = candidate_item.max_life * 1.5 + cand_res_sum * 2.0 + candidate_item.spell_suppression_pct * 3.0

        base_ehp = max(1.0, curr_ehp_score)
        ehp_delta_pct = round(((cand_ehp_score - curr_ehp_score) / base_ehp) * 100.0, 1)

        resist_warning = None
        if player_current_resists:
            delta_fire = candidate_item.fire_res - current_item.fire_res
            delta_cold = candidate_item.cold_res - current_item.cold_res
            delta_light = candidate_item.lightning_res - current_item.lightning_res

            if player_current_resists.get("fire", 75) + delta_fire < 75:
                resist_warning = "CẢNH BÁO: Tháo đồ cũ sẽ làm Kháng Lửa tụt dưới trần 75%!"
            elif player_current_resists.get("cold", 75) + delta_cold < 75:
                resist_warning = "CẢNH BÁO: Tháo đồ cũ sẽ làm Kháng Băng tụt dưới trần 75%!"
            elif player_current_resists.get("lightning", 75) + delta_light < 75:
                resist_warning = "CẢNH BÁO: Tháo đồ cũ sẽ làm Kháng Lôi tụt dưới trần 75%!"

        total_utility = (dps_delta_pct * self.weight_dps) + (ehp_delta_pct * self.weight_ehp)

        if resist_warning:
            total_utility -= 30.0

        if total_utility >= 10.0:
            winner = "CANDIDATE"
            decision = "EQUIP_UPGRADE"
            headline = f"ĐỒ MỚI TỐT HƠN VƯỢT TRỘI (+{total_utility:.1f} điểm)"
            reason = (
                f"Món đồ mới mang lại sát thương vượt trội (DPS: {dps_delta_pct:+g}%) "
                f"và chỉ số sinh tồn (EHP: {ehp_delta_pct:+g}%). Khuyến nghị mặc ngay."
            )
            salvage_advice = "Đồ cũ có thể đưa vào Bàn Phân Giải Thợ Rèn (SALVAGE_BENCH) để rã lấy Vàng & Crafting Dust."
        elif total_utility <= -8.0:
            winner = "CURRENT"
            decision = "KEEP_CURRENT"
            headline = f"ĐỒ HIỆN TẠI TỐT HƠN NHIỀU (Đồ mới kém {-total_utility:.1f} điểm)"
            reason = (
                f"Món đồ mới làm suy giảm nghiêm trọng chỉ số chiến đấu "
                f"(DPS: {dps_delta_pct:+g}%, EHP: {ehp_delta_pct:+g}%). Tuyệt đối không thay."
            )
            if candidate_item.estimated_trade_value_chaos >= 15.0:
                salvage_advice = f"Cất vào Hòm đồ giao dịch (STASH_FOR_TRADE), định giá khoảng {candidate_item.estimated_trade_value_chaos:.0f} Chaos."
            else:
                salvage_advice = "Rã đồ tại Bàn Thợ Rèn (SALVAGE_BENCH) lấy Vàng trả thuế Faustus."
        else:
            winner = "TIE"
            decision = "KEEP_CURRENT"
            headline = "HAI MÓN ĐỒ NGANG NGỬA NHAU"
            reason = f"Độ chênh lệch hữu dụng không đáng kể ({total_utility:+.1f} điểm). Nên ưu tiên món đồ có nhiều kháng hoặc socket ngọc hơn."
            salvage_advice = "Lưu vào hòm đồ dự phòng nếu cần bù kháng cho các bản đồ đặc thù."

        return ItemComparisonResult(
            winner=winner,
            decision=decision,
            utility_delta=round(total_utility, 1),
            dps_delta_pct=dps_delta_pct,
            ehp_delta_pct=ehp_delta_pct,
            resist_impact_warning=resist_warning,
            headline_verdict=headline,
            detailed_reasoning=reason,
            salvage_or_trade_advice=salvage_advice
        )

    def compare_farming_activities(self, current_gold: int, available_divine: float) -> Dict[str, Any]:
        options: list[dict[str, Any]] = [
            {
                "activity": "SEKHEMA_CARRY",
                "title": "Chạy Dịch Vụ Sekhema Trial Carry",
                "profit_div_per_hour": 13.5,
                "gold_tax_needed": 16000,
                "capital_required_div": 3.2,
                "risk": "Thấp (Yêu cầu build đủ cứng để không chết)"
            },
            {
                "activity": "WAYSTONE_T16_SPEEDRUN",
                "title": "Cày Tốc Độ Waystone T16 (Speed Mapping)",
                "profit_div_per_hour": 6.5,
                "gold_tax_needed": 0,
                "capital_required_div": 0.5,
                "risk": "Rất Thấp (Nguồn cày Vàng chính cho tài khoản)"
            },
            {
                "activity": "FAUSTUS_ARBITRAGE",
                "title": "Buôn Chênh Lệch Ngọc & Omen Trên Sàn Faustus",
                "profit_div_per_hour": 9.0,
                "gold_tax_needed": 25000,
                "capital_required_div": 5.0,
                "risk": "Trung Bình (Phụ thuộc biến động giá theo giờ)"
            }
        ]

        for opt in options:
            gold_needed = int(opt["gold_tax_needed"])
            cap_needed = float(opt["capital_required_div"])
            opt["is_feasible"] = (
                current_gold >= gold_needed and
                available_divine >= cap_needed
            )

        feasible_options = [o for o in options if o["is_feasible"]]
        if feasible_options:
            best_opt = max(feasible_options, key=lambda x: float(x["profit_div_per_hour"]))
            verdict = f"HOẠT ĐỘNG TỐT NHẤT: {best_opt['title']} ({best_opt['profit_div_per_hour']} Div/h)"
            explanation = f"Bạn đang có đủ {current_gold:,} Vàng và {available_divine:.1f} Divine để trả phí và vốn. Hoạt động này cho tỷ suất sinh lời tối ưu nhất."
        else:
            best_opt = options[1]
            verdict = f"HOẠT ĐỘNG TỐT NHẤT: {best_opt['title']}"
            explanation = f"Quỹ vàng hiện tại ({current_gold:,} Vàng) không đủ để trả thuế sàn. Chạy Waystone T16 để nhặt vàng là lựa chọn sinh tồn tối thượng lúc này."

        return {
            "recommended_activity": best_opt["activity"],
            "headline_verdict": verdict,
            "explanation": explanation,
            "all_options": options
        }
