from collections import defaultdict

from axelrod.action import Action

from axelrod.player import Player

C, D = Action.C, Action.D

class Retaliate(Player):
    """
    A player starts by cooperating but will retaliate once the opponent
    has won more than 10 percent times the number of defections the player has.

    Names:

    - Retaliate: Original name by Owen Campbell
    """

    name = "Retaliate"
    classifier = {
        "memory_depth": float("inf"),  # Long memory
        "stochastic": False,
        "inspects_source": False,
        "long_run_time": False,
        "manipulates_source": False,
        "manipulates_state": False,
    }

    def __init__(self, retaliation_threshold: float = 0.1) -> None:
        """
        Uses the basic init from the Player class, but also set the name to
        include the retaliation setting.
        """
        super().__init__()
        self.retaliation_threshold = retaliation_threshold
        self.play_counts = defaultdict(int)  # type: defaultdict

    def strategy(self, opponent: Player) -> Action:
        """
        If the opponent has played D to my C more often than x% of the time
        that I've done the same to him, play D. Otherwise, play C.
        """

        if len(self.history):
            last_round = (self.history[-1], opponent.history[-1])
            self.play_counts[last_round] += 1
        CD_count = self.play_counts[(C, D)]
        DC_count = self.play_counts[(D, C)]
        if CD_count > DC_count * self.retaliation_threshold:
            return D
        return C