#!/usr/bin/env python
# _*_ coding: UTF-8 _*_
"""
@Project : 1-最新算法代码
@File : results_collection.py
@Author: wangjingbo
@Date: 2024/8/30 10:20
"""
from typing import Dict, List, Tuple


class BaseResultsCollection:
    """统计仿真引擎运行一局的胜负信息，为后续对手选择等模块调用"""

    def __init__(self):
        self.results_collection: Dict[str, Dict[str, list]] = {}

    def add_opponent(self, opponent_name: str, worker_index: str) -> None:
        """
        添加新的对手策略及worker信息
        Args:
            opponent_name: 对手策略名称
            worker_index: 进程序号
        Returns:
            新的结果汇总字典
        """
        if opponent_name not in self.results_collection:
            self.results_collection[opponent_name]: dict = {}
        if worker_index not in self.results_collection[opponent_name]:
            self.results_collection[opponent_name][worker_index]: list = []

    def update_results(self, opponent_name: str, worker_index: str, result: int) -> None:
        """
        更新结果至结果汇总字典中
        Args:
            opponent_name: 对手策略名称
            worker_index: 进程序号
            result: 对局结果
        Returns:
            新的结果汇总字典
        """
        if opponent_name in self.results_collection and worker_index in self.results_collection[opponent_name]:
            self.results_collection[opponent_name][worker_index].append(result)

    def get_opponent_result(self, opponent_name: str) -> float:
        """
        从结果汇总字典中提取指定策略的最终结果
        Args:
            opponent_name: 对手策略名称
        Returns:
            对手策略的胜率
        """
        results_list: List[int] = []
        for worker_index, worker_results in self.results_collection[opponent_name].items():
            results_list.extend(worker_results)
        win_episode_num: int = results_list.count(1)
        win_rate: float = win_episode_num / len(results_list)

        return win_rate

    def get_all_opponent_results(self) -> Tuple[list, list]:
        """
        从结果汇总字典中提取所有策略的最终结果
        Returns:
            所有对手的胜率
        """
        opponent_names: List[str] = []
        opponent_results: List[float] = []
        for opponent_name, opponent_result in self.results_collection.items():
            win_rate: float = self.get_opponent_result(opponent_name)
            opponent_names.append(opponent_name)
            opponent_results.append(win_rate)

        return opponent_names, opponent_results
