import os
import sys
import glob
base_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..'))
sys.path.append(base_path)

from utils.utils import load_data_and_check_quantity, create_folder_overwrite_if_exist

# 数据量
ENV_NAME = 'TSP_V4'
num_problem = 0
num_episode = 0

# 获取指定环境的所有数据集   
file_list = glob.glob(os.path.join(f'{base_path}/data/used/{ENV_NAME}', '*.pkl'))
file_names = [os.path.basename(file) for file in file_list]
#file_names = [name for name in file_names if 'tsp20' in name]

# 加载数据 & 打印样本量
file_data = load_data_and_check_quantity(file_names, ENV_NAME, num_problem, num_episode, check_ave_obj=True)

# 写数据集 log 文件
create_folder_overwrite_if_exist(f'{base_path}/visualize/dataset/{ENV_NAME}')
for file_name in file_names:
    data_name = file_name[:-4]
    # 可视化评估问题
    if data_name.endswith('problem'):
        problems = file_data[data_name]
        with open(f'{base_path}/visualize/dataset/{ENV_NAME}/{data_name}.txt', 'w') as file:
            #for i, obs in enumerate(problems):
            for i in range(len(problems.answer_list)):
                file.write('-'*25+f' problem-{i} '+'-'*25+'\n')
                obs = problems.problem_list[i]
                answer = problems.answer_list[i]
                position = obs['position'].reshape((-1, 2))

                file.write(f'city position:\n{position}\n\n')
                file.write(f'solution:      \t{answer}\n\n')                     

                if i == num_problem:
                    break

    # 可视化训练序列
    else:
        episodes = file_data[data_name]
        with open(f'{base_path}/visualize/dataset/{ENV_NAME}/{data_name}.txt', 'w') as file:
            for i, epi in enumerate(episodes):
                acts = epi['actions']
                rewards = epi['rewards']
                obss = epi['observations']

                file.write('-'*25+f' episode-{i} '+'-'*25+'\n')
                for t in range(len(rewards)):
                    node_info = obss['node_info'][t].reshape((-1, 3))
                    current_location = obss['current_position'][t]
                    file.write(f'node info:\n{node_info}\n')
                    file.write(f'current location:\t{current_location}\n')
                    file.write(f'take action:     \t{acts[t]}\n')
                    file.write(f'get reward:      \t{rewards[t]}\n\n')

                if i == num_episode:
                    break

    print(f'{data_name}.txt saved')