
"""
The MIT License

Copyright (c) 2022 SGBS

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.



THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""


import torch
import pickle

from CVRPEnv import CVRPEnv, get_random_problems, augment_xy_data_by_8_fold

class E_CVRPEnv(CVRPEnv):

    # def __init__(self, **model_params):
    #     super().__init__(**model_params)

    def load_problems_by_index(self, start_index, batch_size, aug_factor=1):
        self.batch_size = batch_size

        if not self.FLAG__use_saved_problems:
            depot_xy, node_xy, is_xy, node_demand = get_random_problems(batch_size, self.problem_size,
                                                                        self.intermediate_stop_size)
        else:
            depot_xy = self.saved_depot_xy[self.saved_index:self.saved_index + batch_size]
            node_xy = self.saved_node_xy[self.saved_index:self.saved_index + batch_size]
            is_xy = self.saved_is_xy[self.saved_index:self.saved_index + batch_size]
            node_demand = self.saved_node_demand[self.saved_index:self.saved_index + batch_size]
            self.saved_index += batch_size

        if aug_factor > 1:
            if aug_factor == 8:
                self.batch_size = self.batch_size * 8
                depot_xy = augment_xy_data_by_8_fold(depot_xy)
                node_xy = augment_xy_data_by_8_fold(node_xy)
                is_xy = augment_xy_data_by_8_fold(is_xy)
                node_demand = node_demand.repeat(8, 1)
            else:
                raise NotImplementedError
        self.depot_xy = depot_xy
        self.depot_node_xy = torch.cat((depot_xy, node_xy), dim=1)
        self.depot_node_is_xy = torch.cat((depot_xy, node_xy, is_xy), dim=1)
        self.is_xy = is_xy
        self.max_travel_distance = torch.ones(size=(self.batch_size, 1)) * 4
        depot_demand = torch.zeros(size=(self.batch_size, 1))
        is_demand = torch.zeros(size=(self.batch_size, is_xy.size(1)))
        self.depot_node_demand = torch.cat((depot_demand, node_demand), dim=1)
        self.depot_node_is_demand = torch.cat((depot_demand, node_demand, is_demand), dim=1)
        # shape: (batch, problem+1)

        self.BATCH_IDX = torch.arange(self.batch_size)[:, None].expand(self.batch_size, self.pomo_size)
        self.POMO_IDX = torch.arange(self.pomo_size)[None, :].expand(self.batch_size, self.pomo_size)
        self.IS_IDX = torch.arange(self.problem_size + 1, self.problem_size + self.intermediate_stop_size + 1)[None,
                      :].expand(
            self.batch_size, self.intermediate_stop_size)

        self.reset_state.depot_xy = depot_xy
        self.reset_state.is_xy = is_xy
        self.reset_state.node_xy = node_xy
        self.reset_state.whole_nodes = torch.cat((depot_xy, node_xy, is_xy), -2)
        self.reset_state.node_demand = node_demand

        self.step_state.Is_IDX = self.IS_IDX
        self.step_state.BATCH_IDX = self.BATCH_IDX
        self.step_state.POMO_IDX = self.POMO_IDX
        diff = self.depot_node_is_xy.unsqueeze(2) - self.depot_node_is_xy.unsqueeze(1)
        self.step_state.distances = - torch.norm(diff, dim=-1)
        self.reset_state.distances = self.step_state.distances

        diff = self.depot_node_xy.unsqueeze(2) - self.depot_node_xy.unsqueeze(1)
        self.step_state.node_distances = - torch.norm(diff, dim=-1)

        diff = self.is_xy.unsqueeze(2) - self.is_xy.unsqueeze(1)
        self.step_state.is_distances = - torch.norm(diff, dim=-1)

        factor = 10_00
        diff2 = self.depot_node_is_xy.unsqueeze(2) - self.depot_xy.unsqueeze(1)
        distance_from_all_nodes_to_depot = torch.norm(diff2, dim=-1).squeeze(-1)[:, None, :].expand(self.batch_size,
                                                                                                    self.pomo_size,
                                                                                                    self.depot_node_is_xy.size(
                                                                                                        1))
        self.distance_from_all_nodes_to_depot = (distance_from_all_nodes_to_depot * factor).int().float() / factor

        shift_coors = self.depot_node_is_xy - self.depot_node_is_xy[:, 0:1, :]
        _x, _y = shift_coors[:, :, 0], shift_coors[:, :, 1]
        r = torch.sqrt(_x ** 2 + _y ** 2)
        theta = torch.atan2(_y, _x)
        x = torch.stack((r, theta, self.depot_node_is_demand), -1)
        x_depot = x[:, 0:1, :]
        x_node = x[:, 1:-self.intermediate_stop_size, :]
        x_is = x[:, -self.intermediate_stop_size:, 0:2]
        shift_coors_without_is = self.depot_node_xy - self.depot_node_xy[:, 0:1, :]
        self.reset_state.shift_coors = shift_coors_without_is
        self.reset_state.x_depot = x_depot
        self.reset_state.x_node = x_node
        self.reset_state.x_is = x_is

        r_min = r[:, 1:-self.intermediate_stop_size].min(dim=-1, keepdim=True).values
        r_max = r[:, 1:-self.intermediate_stop_size].max(dim=-1, keepdim=True).values
        r_norm = (r[:, 1:-self.intermediate_stop_size] - r_min) / (r_max - r_min + 1e-8)
        theta2 = theta % (2 * torch.pi)
        theta_min = theta2[:, 1:-self.intermediate_stop_size].min(dim=-1, keepdim=True).values
        theta_max = theta2[:, 1:-self.intermediate_stop_size].max(dim=-1, keepdim=True).values
        theta_norm = (theta2[:, 1:-self.intermediate_stop_size] - theta_min) / (theta_max - theta_min + 1e-8)

        weights = torch.linspace(0, 1, steps=self.number_of_locality_att)  # shape: (n,)
        weight_A = weights.view(1, self.number_of_locality_att, 1)  # shape: (n, 1, 1)
        weight_B = (1 - weights).view(1, self.number_of_locality_att, 1)  # shape: (n, 1, 1)

        # Step 2: Apply weights and sum A and B
        # Expand A and B to shape: (1, 2, 111) → broadcast to (n, 2, 111)
        A_exp = r_norm.unsqueeze(1)  # (1, 2, 111)
        B_exp = theta_norm.unsqueeze(1)
        output = (weight_A * A_exp + weight_B * B_exp)  # shape: (n, 2, 111)
        _, sorted_indices = torch.sort(output, dim=-1)
        half_bucket = int(self.bucket_size / 2)
        x_reordered = torch.cat((sorted_indices[:, :, half_bucket:], sorted_indices[:, :, :half_bucket]), dim=-1)
        sorted_indices = torch.cat((sorted_indices, x_reordered), dim=1)

        total = sorted_indices.shape[-1]
        num_buckets = total // self.bucket_size
        sorted_indices = sorted_indices[:, :, :num_buckets * self.bucket_size]  # remove extra
        bucketed_indices = sorted_indices.view(self.batch_size, self.number_of_locality_att * 2, num_buckets,
                                               self.bucket_size) + 1
        zero_padding = torch.zeros(bucketed_indices.size(0), bucketed_indices.size(1), bucketed_indices.size(2), 1,
                                   dtype=bucketed_indices.dtype, device=bucketed_indices.device)
        bucketed_indices = torch.cat([zero_padding, bucketed_indices], dim=-1)
        # shift_coors = self.depot_node_is_xy.unsqueeze(2) - self.depot_node_is_xy.unsqueeze(1)
        # r = torch.sqrt(torch.sum(shift_coors ** 2, dim=-1))  # Shape: (2, 100, 100)
        # theta = torch.atan2(shift_coors[..., 1], shift_coors[..., 0])
        self.reset_state.buckets = bucketed_indices
        self.reset_state.sorted_indices = sorted_indices
        self.step_state.xy = self.depot_node_is_xy
        self.step_state.theta = theta
        self.step_state.r = r
        self.step_state.norm_demand = self.depot_node_is_demand
        # self.step_state.whole_theta = theta[:, None, :, :].expand(theta.size(0), self.pomo_size, theta.size(1),
        #                                                           theta.size(2))
        # self.step_state.whole_dist = r[:, None, :, :].expand(r.size(0), self.pomo_size, r.size(1), r.size(2))


    def modify_pomo_size(self, new_pomo_size):
        self.pomo_size = new_pomo_size
        self.BATCH_IDX = torch.arange(self.batch_size)[:, None].expand(self.batch_size, self.pomo_size)
        self.POMO_IDX = torch.arange(self.pomo_size)[None, :].expand(self.batch_size, self.pomo_size)
        self.step_state.BATCH_IDX = self.BATCH_IDX
        self.step_state.POMO_IDX = self.POMO_IDX

    def use_pkl_saved_problems(self, filename, num_problems, index_begin=0):
        self.FLAG__use_saved_problems = True

        with open(filename, 'rb') as pickle_file:
            data = pickle.load(pickle_file)
        depot_data = list(data["depot_xy"][i] for i in range(index_begin, index_begin+num_problems) )
        self.saved_depot_xy = torch.stack(depot_data)

        node_data = list(data["node_xy"][i] for i in range(index_begin, index_begin+num_problems))
        self.saved_node_xy = torch.stack(node_data)

        # shape: (batch, problem, 2)

        demand_data = list(data["node_demand"][i] for i in range(index_begin, index_begin+num_problems))
        self.saved_node_demand = torch.stack(demand_data)
        is_xy_data =  list(data["is_xy"][i] for i in range(index_begin, index_begin+num_problems) )
        self.saved_is_xy = torch.stack(is_xy_data)
        self.saved_index = 0

    def reset_by_repeating_bs_env(self, bs_env, repeat):
        self.selected_count = bs_env.selected_count
        self.current_node = bs_env.current_node.repeat_interleave(repeat, dim=1)
        # self.distance_from_all_nodes_to_depot= bs_env.distance_from_all_nodes_to_depot.repeat_interleave(repeat, dim=1)
        # self.time = bs_env.time.repeat_interleave(repeat, dim=1)
        # shape: (batch, pomo)
        self.remaining_travel_distance = bs_env.remaining_travel_distance.repeat_interleave(repeat, dim=1)
        self.last_node_index =  bs_env.last_node_index.repeat_interleave(repeat, dim=1)
        self.selected_node_list = bs_env.selected_node_list.repeat_interleave(repeat, dim=1)
        # shape: (batch, pomo, 0~)

        self.at_the_depot = bs_env.at_the_depot.repeat_interleave(repeat, dim=1)
        self.at_is = bs_env.at_is.repeat_interleave(repeat, dim=1)
        # shape: (batch, pomo)

        self.load = bs_env.load.repeat_interleave(repeat, dim=1)
        # shape: (batch, pomo)
        self.visited_ninf_flag = bs_env.visited_ninf_flag.repeat_interleave(repeat, dim=1)
        # shape: (batch, pomo, problem+1)
        self.ninf_mask = bs_env.ninf_mask.repeat_interleave(repeat, dim=1)
        # shape: (batch, pomo, problem+1)
        self.finished = bs_env.finished.repeat_interleave(repeat, dim=1)
        # shape: (batch, pomo)

    def reset_by_gathering_rollout_env(self, rollout_env, gathering_index):
        self.selected_count = rollout_env.selected_count
        self.current_node = rollout_env.current_node.gather(dim=1, index=gathering_index)
        # shape: (batch, pomo)
        exp_gathering_index = gathering_index[:, :, None].expand(-1, -1, self.selected_count)
        self.selected_node_list = rollout_env.selected_node_list.gather(dim=1, index=exp_gathering_index)
        # shape: (batch, pomo, 0~)

        self.at_the_depot = rollout_env.at_the_depot.gather(dim=1, index=gathering_index)
        self.at_is = rollout_env.at_is.gather(dim=1, index=gathering_index)
        # shape: (batch, pomo)
        self.remaining_travel_distance = rollout_env.remaining_travel_distance.gather(dim=1, index=gathering_index)
        ss = gathering_index.unsqueeze(-1)
        try:
            self.last_node_index = rollout_env.last_node_index.gather(dim=1, index=ss)
        except :
            print("ssdfs")
        self.load = rollout_env.load.gather(dim=1, index=gathering_index)
        # self.distance_from_all_nodes_to_depot = rollout_env.distance_from_all_nodes_to_depot.gather(dim=2, index=ss)

        # try:
        #     self.time = rollout_env.time.gather(dim=1, index=gathering_index)
        # except:
        #     print("sdfasdfasdfsadf")
        # shape: (batch, pomo)
        exp_gathering_index = gathering_index[:, :, None].expand(-1, -1, self.problem_size+1 + self.intermediate_stop_size)
        self.visited_ninf_flag = rollout_env.visited_ninf_flag.gather(dim=1, index=exp_gathering_index)
        # shape: (batch, pomo, problem+1)
        self.ninf_mask = rollout_env.ninf_mask.gather(dim=1, index=exp_gathering_index)
        # shape: (batch, pomo, problem+1)
        self.finished = rollout_env.finished.gather(dim=1, index=gathering_index)
        # shape: (batch, pomo)

        if gathering_index.size(1) != self.pomo_size:
            self.modify_pomo_size(gathering_index.size(1))

    def merge(self, other_env):

        self.current_node = torch.cat((self.current_node, other_env.current_node), dim=1)
        # shape: (batch, pomo1 + pomo2)
        self.selected_node_list = torch.cat((self.selected_node_list, other_env.selected_node_list), dim=1)
        # shape: (batch, pomo1 + pomo2, 0~)

        self.at_the_depot = torch.cat((self.at_the_depot, other_env.at_the_depot), dim=1)
        self.at_is = torch.cat((self.at_is, other_env.at_is), dim=1)
        # shape: (batch, pomo1 + pomo2)
        self.load = torch.cat((self.load, other_env.load), dim=1)
        self.last_node_index = torch.cat((self.last_node_index, other_env.last_node_index), dim=1)
        self.remaining_travel_distance = torch.cat((self.remaining_travel_distance, other_env.remaining_travel_distance), dim=1)
        # self.distance_from_all_nodes_to_depot = torch.cat((self.distance_from_all_nodes_to_depot, other_env.distance_from_all_nodes_to_depot), dim=1)
        # self.time = torch.cat((self.time, other_env.time), dim=1)
        # shape: (batch, pomo1 + pomo2)
        self.visited_ninf_flag = torch.cat((self.visited_ninf_flag, other_env.visited_ninf_flag), dim=1)
        # shape: (batch, pomo1 + pomo2, problem+1)
        self.ninf_mask = torch.cat((self.ninf_mask, other_env.ninf_mask), dim=1)
        # shape: (batch, pomo1 + pomo2, problem+1)
        self.finished = torch.cat((self.finished, other_env.finished), dim=1)
        # shape: (batch, pomo1 + pomo2)