import os

solution_filename = "./solutions"
tsplib_dir = "./tsp/tsplib"

# get solutions
solutions = {}
with open(solution_filename, "r") as f:
    lines = f.readlines()
    for line in lines:
        line = line.split()
        dataset_name = line[0]
        solution = line[2]
        # print(line)
        solutions[dataset_name] = solution
# print(solutions)


filenames = os.listdir(tsplib_dir)
# print(filenames)
out_f_path = os.path.join("./tsp", "tsp_realworld_test.txt")
out_lines = {}
for filename in filenames:
    file_path = os.path.join(tsplib_dir, filename)
    with open(file_path, "r") as f:
        lines = f.readlines()
        lines = lines[6:-2]
        coords = ""
        tour = ""
        for line in lines:
            data = line.split()
            # print(data)
            coords = coords + ' ' + data[1] + ' ' + data[2] + ' '
            tour = tour + ' ' + data[0] + ' '
        coords = coords.strip()
        tour = tour.strip()
        # print(coords)
        # print(tour)
        dataset_name = filename.split('.')[0]
        solution = solutions[dataset_name]
        out_line = coords + ' output ' + tour + ' output ' + solution + ' output ' + dataset_name + '\n'
    out_lines[dataset_name] = out_line
    # print(out_line)

namelist = ["eil51", "berlin52", "st70", "eil76", "pr76", "rat99", "kroA100", \
    "kroB100", "kroC100", "kroD100", "kroE100", "rd100", "eil101", "lin105", "pr107", \
    "pr124", "bier127", "ch130", "pr136", "pr144", "ch150", "kroA150", "kroB150", \
    "pr152", "u159", "rat195", "d198", "kroA200", "kroB200"]

# write lines to out file
with open(out_f_path, "w") as f:
    for name in namelist:
        f.write(out_lines[name])