"""WealthTracker - Agent 财富追踪，用于拍卖机制"""

from __future__ import annotations


class WealthTracker:
    """Track agent wealth for auction mechanism.

    Agents earn wealth by completing tasks successfully.
    Agents lose wealth by failing tasks.
    Bankrupt agents (wealth <= -100) are excluded from auctions.
    """

    def __init__(self, initial_wealth: float = 100.0) -> None:
        self._balances: dict[str, float] = {}
        self._initial_wealth = initial_wealth

    def get_wealth(self, agent_name: str) -> float:
        """Get agent's current wealth, defaulting to initial_wealth"""
        return self._balances.get(agent_name, self._initial_wealth)

    def reward(self, agent_name: str, amount: float) -> None:
        """Reward agent for successful task completion"""
        current = self.get_wealth(agent_name)
        self._balances[agent_name] = current + amount

    def penalize(self, agent_name: str, amount: float) -> None:
        """Penalize agent for task failure"""
        current = self.get_wealth(agent_name)
        self._balances[agent_name] = current - amount

    def is_bankrupt(self, agent_name: str) -> bool:
        """Check if agent is bankrupt (wealth <= -100)"""
        return self.get_wealth(agent_name) <= -100

    def reset(self, agent_name: str) -> None:
        """Reset agent's wealth to initial value"""
        self._balances[agent_name] = self._initial_wealth

    def get_rankings(self) -> list[tuple[str, float]]:
        """Get wealth rankings sorted by wealth descending"""
        all_agents = [
            (name, wealth) for name, wealth in self._balances.items()
        ]
        all_agents.sort(key=lambda x: x[1], reverse=True)
        return all_agents

    def get_wealth_factor(self, agent_name: str) -> float:
        """Get wealth factor for scoring: 1.0 + (wealth / 1000.0)"""
        return 1.0 + (self.get_wealth(agent_name) / 1000.0)
