"""
EvaluateAgentUsecase
학습된 Q-Table의 성능을 평가하는 Usecase
"""

from typing import Optional
from ..domain.model.q_table import QTable
from ..domain.repository.experience_repository import ExperienceRepository


class EvaluateAgentUsecase:
    """
    저장된 Experience 데이터를 사용하여 현재 에이전트(Q-Table)의 성능을 평가
    """

    def __init__(
        self,
        q_table: QTable,
        experience_repository: ExperienceRepository,
    ):
        """
        Args:
            q_table: 평가할 Q-Table
            experience_repository: Experience 저장소
        """
        self.q_table = q_table
        self.experience_repository = experience_repository

    def execute(
        self, filename: str = "experiences.jsonl", sample_size: Optional[int] = None
    ) -> dict:
        """
        현재 Q-Table의 성능 평가

        Args:
            filename: 평가용 Experience 파일
            sample_size: 샘플링 크기 (None이면 전체)

        Returns:
            {
                'avg_q_value': 0.5,
                'avg_reward': 1.0,
                'total_samples': 100
            }
        """
        experiences = self.experience_repository.load_all(filename)

        if not experiences:
            return {"avg_q_value": 0.0, "avg_reward": 0.0, "total_samples": 0}

        # 샘플링
        if sample_size and sample_size < len(experiences):
            import random

            experiences = random.sample(experiences, sample_size)

        total_q_value = 0.0
        total_reward = 0.0

        for exp in experiences:
            state_index = exp.state.to_index()
            q_value = self.q_table.get_q_value(state_index, exp.action_id)
            total_q_value += q_value
            total_reward += exp.reward

        n = len(experiences)

        return {
            "avg_q_value": total_q_value / n,
            "avg_reward": total_reward / n,
            "total_samples": n,
        }
