import time


def evalRun_one_episode(env, agent, agent_name="random", max_steps_per_episode=100):
    """
        Runs one episode with the given configuration 

        Args:
            env: recommendation gym environnement
            agent: recommendation agent (Full Slate-Q-learning || Rnadom/naive agent)
            agent_name: name of the chosen agent ('random' || 'fsq')

        Returns:

            step_number: length of the episode
            total_reward: total watching_time and quality for this episode
            time_dif: execution time of this episode
            total_qual/step_number: Average total quality of the episode
            q_videos: list of videos (clicked throughout the episdoe) qualities 
            w_videos: list of videos (clicked throughout the episdoe) watching time

        """
    observation = env.reset()
    action = agent.begin_episode(observation)
    step_number = 0
    total_watch = 0.
    q_videos = []
    w_videos = []
    total_qual = 0
    start_time = time.time()
    total_length_videos = 0
    while True:
        observation, reward, done, info, _ = env.step(action)

        for j in range(len(observation['response'])):
            if observation['response'][j]['click'] == 1:
                index = action[j]
                total_length_videos += list(observation['doc'].values())[index][-1]
                total_watch += reward[1]
                total_qual += reward[0]
                q_videos += [reward[0]]
                w_videos += [reward[1]]

        # Update environment-specific metrics with responses to the slate.
        env.update_metrics(observation['response'], info)
        step_number += 1

        if done:
            break
        elif step_number == max_steps_per_episode:
            # Stop the run loop once we reach the true end of episode.
            break
        else:
            if agent_name == "random":
                action = agent.step(observation)
            elif agent_name == "fsq":
                action = agent.step(reward[1], observation)
            else:
                print("agent name is not correct, please select (random || fsq))")

    agent.end_episode(reward[1], observation)
    time_diff = time.time() - start_time

    return step_number, total_watch, time_diff, total_qual/step_number, q_videos, w_videos