# 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

torch, nn = try_import_torch()

# from marllib.marl.models.zoo.encoder.base_encoder import BaseEncoder
from marllib.marl.models.zoo.tree.tree_utils import TreeLSTM, extract_features

class BaseTree(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")

        # TODO: read size from file
        agent_attr_sz = 83
        node_sz = 12
        hidden_sz = 128
        tree_embedding_sz = 128

        # actor
        self.p_tree_lstm = TreeLSTM(node_sz, tree_embedding_sz)
        self.p_attr_embedding = nn.Sequential(
                nn.Linear(agent_attr_sz, 2 * hidden_sz),
                nn.GELU(),
                nn.Linear(2 * hidden_sz, 2 * hidden_sz),
                nn.GELU(),
                nn.Linear(2 * hidden_sz, 2 * hidden_sz),
                nn.GELU(),
                nn.Linear(2 * hidden_sz, hidden_sz),
                nn.GELU(),
            )
        self.p_branch = SlimFC(
            in_size=hidden_sz + tree_embedding_sz,
            out_size=num_outputs,
            initializer=normc_initializer(0.01),
            activation_fn=None)

        # critic
        self.vf_tree_lstm = TreeLSTM(node_sz, tree_embedding_sz)
        self.vf_attr_embedding = nn.Sequential(
                nn.Linear(agent_attr_sz, 2 * hidden_sz),
                nn.GELU(),
                nn.Linear(2 * hidden_sz, 2 * hidden_sz),
                nn.GELU(),
                nn.Linear(2 * hidden_sz, 2 * hidden_sz),
                nn.GELU(),
                nn.Linear(2 * hidden_sz, hidden_sz),
                nn.GELU(),
            )

        # self.vf_encoder = nn.Sequential(*copy.deepcopy(layers))
        self.vf_branch = SlimFC(
            in_size=hidden_sz + tree_embedding_sz,
            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_tree_lstm, self.p_attr_embedding, 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]):

        # TODO: mask
        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()

        self.inputs = flat_inputs
        agent_attr, forest, adjacency, node_order, edge_order = extract_features(self.inputs)

        # policy encoder
        # self._features = self.p_encoder(self.inputs)
        agent_attr_embedding = self.p_attr_embedding(agent_attr) # [bs, hidden_sz]
        tree_embedding = self.p_tree_lstm(forest, adjacency, node_order, edge_order) # [bs,1,tree_embedding_sz]
        tree_embedding = tree_embedding.squeeze(1)

        self._features = torch.cat([agent_attr_embedding, tree_embedding], dim=-1) # [bs, hidden_dim]

        # policy output
        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]
        agent_attr, forest, adjacency, node_order, edge_order = extract_features(self.inputs)

        agent_attr_embedding = self.vf_attr_embedding(agent_attr) # [bs, hidden_sz]
        tree_embedding = self.vf_tree_lstm(forest, adjacency, node_order, edge_order) # [bs,1,tree_embedding_sz]
        tree_embedding = tree_embedding.squeeze(1)

        features = torch.cat([agent_attr_embedding, tree_embedding], dim=-1) # [bs, hidden_dim]
        x = self.vf_branch(features)

        if self.q_flag:
            return torch.reshape(x, [B, -1])
        else:
            return torch.reshape(x, [-1])

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

    def critic_parameters(self):
        critics = [self.vf_tree_lstm, self.vf_attr_embedding, self.vf_branch]
        return reduce(lambda x, y: x + y, map(lambda p: list(p.parameters()), critics))


