"""
Quản lý Số dư Vàng & Tính Toán Thuế Chợ Hối Đoái POE2 (Gold & Tax Tracker)
"""

from typing import Callable, List

from src.assistant_tool.config import Config


class GoldTracker:
    def __init__(self, initial_gold: int = 50000):
        self._current_gold = max(0, initial_gold)
        self._listeners: List[Callable[[int], None]] = []

    @property
    def current_gold(self) -> int:
        return self._current_gold

    def register_listener(self, callback: Callable[[int], None]) -> None:
        """Đăng ký hàm callback nhận thông báo khi số dư Vàng thay đổi."""
        self._listeners.append(callback)

    def _notify(self) -> None:
        for cb in self._listeners:
            try:
                cb(self._current_gold)
            except Exception:
                pass

    def set_gold(self, amount: int) -> None:
        """Đặt giá trị số dư vàng."""
        self._current_gold = max(0, amount)
        self._notify()

    def add_gold(self, amount: int) -> None:
        """Cộng thêm vàng (nhặt được từ map hoặc bán đồ ve chai)."""
        self._current_gold += amount
        self._notify()

    def deduct_tax(self, category: str, quantity: int = 1) -> bool:
        """Trừ thuế vàng khi người chơi thực hiện 1 giao dịch thành công."""
        tax = self.get_tax_for(category, quantity)
        if self._current_gold >= tax:
            self._current_gold -= tax
            self._notify()
            return True
        return False

    def get_tax_for(self, category: str, quantity: int = 1) -> int:
        """Tính tổng số vàng thuế cần trả cho giao dịch."""
        unit_tax = Config.GOLD_TAX_RATES.get(category, 250)
        return unit_tax * quantity

    def can_afford_tax(self, category: str, quantity: int = 1) -> bool:
        """Kiểm tra xem nhân vật có đủ vàng để trả thuế hay không."""
        return self._current_gold >= self.get_tax_for(category, quantity)

    def max_trades_affordable(self, category: str) -> int:
        """Tính số lượt giao dịch tối đa mà số vàng hiện có gánh được."""
        unit_tax = Config.GOLD_TAX_RATES.get(category, 250)
        if unit_tax <= 0:
            return 9999
        return self._current_gold // unit_tax

    def get_status_description(self) -> str:
        """Đánh giá trạng thái vốn vàng cho việc giao dịch."""
        if self._current_gold < 15000:
            return "Vốn Vàng Thấp (< 15k): Ưu tiên chạy Waystone dọn quái nhặt Vàng trước khi lướt sóng lớn."
        elif self._current_gold < 80000:
            return "Vốn Vàng Vừa Đủ (15k - 80k): Đủ gánh thuế cho 50+ kèo Orbs lẻ hoặc 20 bộ Chìa khóa Boss."
        else:
            return "Vốn Vàng Dồi Dào (> 80k): Trạng thái Đại Gia - Tự do quét gom sỉ Orbs, Sekhema Keys & Omens!"
