# MIT License

# Copyright (c) 2023 Replicable-MARL

# 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.

from ray.rllib.utils.torch_ops import FLOAT_MIN
from functools import reduce
import copy
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.models.torch.misc import SlimFC, SlimConv2d, normc_initializer
from ray.rllib.utils.annotations import override
from ray.rllib.utils.framework import try_import_torch
from ray.rllib.utils.typing import Dict, TensorType, List
from marllib.marl.models.zoo.encoder.base_encoder import BaseEncoder
from marllib.marl.models.zoo.tree.tree_utils import TreeLSTM, extract_features, Transformer

torch, nn = try_import_torch()


class LocalCriticMLP(TorchModelV2, nn.Module):
    """Generic fully connected network."""

    def __init__(
            self,
            obs_space,
            action_space,
            num_outputs,
            model_config,
            name,
            **kwargs,
    ):
        TorchModelV2.__init__(self, obs_space, action_space, num_outputs,
                              model_config, name)
        nn.Module.__init__(self)

        # decide the model arch
        self.custom_config = model_config["custom_model_config"]
        self.full_obs_space = getattr(obs_space, "original_space", obs_space)
        self.n_agents = self.custom_config["num_agents"]
        self.activation = model_config.get("fcnet_activation")

        # actor
        self.p_encoder = BaseEncoder(model_config, self.full_obs_space)

        self.p_branch = SlimFC(
            in_size=self.p_encoder.output_dim,
            out_size=num_outputs,
            initializer=normc_initializer(0.01),
            activation_fn=None)

        # critic
        self.vf_encoder = BaseEncoder(model_config, self.full_obs_space)

        # graph neural network
        num_heads = 4
        self.vf_transformer = Transformer(self.vf_encoder.output_dim, num_heads)

        self.vf_branch = SlimFC(
            in_size=self.vf_encoder.output_dim,
            out_size=1,
            initializer=normc_initializer(0.01),
            activation_fn=None)

        # Holds the current "base" output (before logits layer).
        self._features = None
        # Holds the last input, in case value branch is separate.
        self._last_obs = None

        self.q_flag = False

        self.actors = [self.p_encoder, self.p_branch]
        self.actor_initialized_parameters = self.actor_parameters()


    @override(TorchModelV2)
    def forward(self, input_dict: Dict[str, TensorType],
                state: List[TensorType],
                seq_lens: TensorType) -> (TensorType, List[TensorType]):
        
        if self.custom_config["global_state_flag"] or self.custom_config["mask_flag"]:
            flat_inputs = input_dict["obs"]["obs"].float()
            # Convert action_mask into a [0.0 || -inf]-type mask.
            if self.custom_config["mask_flag"]:
                action_mask = input_dict["obs"]["action_mask"]
                inf_mask = torch.clamp(torch.log(action_mask), min=FLOAT_MIN)
        else:
            flat_inputs = input_dict["obs"]["obs"].float()

        # incoporate other local information
        # self.agent_mask = input_dict["obs"]["agent_mask"].float() # [bs, num_agents]
        # self.last_agent_mask = input_dict["obs"]["last_agent_mask"].float() # [bs, num_agents]

        self.inputs = flat_inputs
        self._features = self.p_encoder(self.inputs)

        output = self.p_branch(self._features)

        if self.custom_config["mask_flag"]:
            output = output + inf_mask

        return output, state

    @override(TorchModelV2)
    def value_function(self, ) -> TensorType:
        assert self._features is not None, "must call forward() first"
        B = self._features.shape[0]
        return torch.zeros((B,), dtype=torch.float32).to(self._features.device)


    def central_value_function(self, state, opponent_actions=None, agent_mask=None) -> TensorType:
        assert self._features is not None, "must call forward() first"
        B = state.shape[0]
        # state: [B, num_agents, obs_dim] 

        # === layer 1: mlp ===
        features = self.vf_encoder(state)
        if agent_mask is None:
            agent_mask = torch.zeros((B, self.n_agents), dtype=torch.float32).to(self._features.device)
        sum_mask = (1 - agent_mask.float()).unsqueeze(-1) # [bs, num_agents, 1]

        # === layer 2: transformer ===
        # M: agent_mask should be bool!
        features = self.vf_transformer(features, agent_mask.bool()) # [bs, num_agents, hid_dim]

        # method 2: sum on features
        # features = torch.sum(features * sum_mask, axis=1) / torch.sum(sum_mask, axis=1) # [bs,hid_dim]   

        # === layer 3: mlp ===
        state_values = self.vf_branch(features) # [bs, num_agents, 1] or [bs, 1]

        # method 1: sum on state_values
        state_values = torch.sum(state_values * sum_mask, axis=1) / torch.sum(sum_mask, axis=1) # [bs, 1]   

        return torch.reshape(state_values, [-1])
        # if self.q_flag:
            # return torch.reshape(self.vf_branch(features), [B, -1])
        # else:
            # return torch.reshape(self.vf_branch(features), [-1])

    def actor_parameters(self):
        return reduce(lambda x, y: x + y, map(lambda p: list(p.parameters()), self.actors))

    def critic_parameters(self):
        # M: should update all parameters
        # return list(self.vf_branch.parameters())
        critics = [self.vf_encoder, self.vf_transformer, self.vf_branch]
        return reduce(lambda x, y: x + y, map(lambda p: list(p.parameters()), critics))

