__credits__ = ["Rushiv Arora"]

import numpy as np

from gymnasium.utils import EzPickle
from gymnasium.envs.mujoco.swimmer_v3 import SwimmerEnv
from gymnasium.spaces import Box
from gymnasium.spaces import Discrete
import envs


DEFAULT_CAMERA_CONFIG = {}


class MOSwimmerEnv(SwimmerEnv, EzPickle):
    metadata = {
        "render_modes": [
            "human",
            "rgb_array",
            "depth_array",
        ],
        "render_fps": 25,
    }

    def __init__(
        self,
        xml_file="swimmer.xml",
        forward_reward_weight=1.0,
        ctrl_cost_weight=1e-4,
        reset_noise_scale=0.1,
        exclude_current_positions_from_observation=True,
        weight=[1.0, 0, 0, 0, 0, 0], 
        **kwargs,
    ):
        self.w = weight
        
        super().__init__(**kwargs)
        EzPickle.__init__(
            self,
            xml_file,
            forward_reward_weight,
            ctrl_cost_weight,
            reset_noise_scale,
            exclude_current_positions_from_observation,
            **kwargs,
        )

        self.reward_dim = 6
        self.reward_space = Box(low=-np.inf, high=np.inf, shape=(self.reward_dim,))

        actions = [-1., -2/3, -1/3, 0, 1/3, 2/3, 1.]
        self.action_dict = dict()
        for a1 in actions:
            for a2 in actions:
                self.action_dict[len(self.action_dict)] = (a1, a2)

    def _set_action_space(self):
        self.action_space = Discrete(49)

    def control_cost(self, action):
        control_cost = self._ctrl_cost_weight * np.sum(np.square(action))
        return control_cost

    def step(self, a):
        action = self.action_dict[a]
        xy_position_before = self.sim.data.qpos[0:2].copy()
        self.do_simulation(action, self.frame_skip)
        xy_position_after = self.sim.data.qpos[0:2].copy()

        xy_velocity = (xy_position_after - xy_position_before) / self.dt
        x_velocity, y_velocity = xy_velocity

        forward_reward = self._forward_reward_weight * x_velocity
        ctrl_cost = self.control_cost(action)

        observation = self._get_obs()
        reward = forward_reward - ctrl_cost
        
        xy_position = xy_position_after - xy_position_before
        phi = np.zeros(6)
        phi[0] = forward_reward
        phi[1] = -ctrl_cost
        phi[2] = xy_position[0]
        phi[3] = xy_position[1]
        phi[4] = x_velocity
        phi[5] = y_velocity

        info = {
            "reward_fwd": forward_reward,
            "reward_ctrl": -ctrl_cost,
            "x_position": xy_position_after[0],
            "y_position": xy_position_after[1],
            "distance_from_origin": np.linalg.norm(xy_position_after, ord=2),
            "x_velocity": x_velocity,
            "y_velocity": y_velocity,
            "forward_reward": forward_reward,
        }

        scalar_reward = np.dot(phi, self.w)

        if self.render_mode == "human":
            self.render()

        return observation, scalar_reward, False, {'phi': phi}

    def _get_obs(self):
        position = self.sim.data.qpos.flat.copy()
        velocity = self.sim.data.qvel.flat.copy()

        if self._exclude_current_positions_from_observation:
            position = position[2:]

        observation = np.concatenate([position, velocity]).ravel()
        return observation

    def reset_model(self):
        noise_low = -self._reset_noise_scale
        noise_high = self._reset_noise_scale

        qpos = self.init_qpos + self.np_random.uniform(
            low=noise_low, high=noise_high, size=self.model.nq
        )
        qvel = self.init_qvel + self.np_random.uniform(
            low=noise_low, high=noise_high, size=self.model.nv
        )

        self.set_state(qpos, qvel)

        observation = self._get_obs()
        return observation

    def viewer_setup(self):
        assert self.viewer is not None
        for key, value in DEFAULT_CAMERA_CONFIG.items():
            if isinstance(value, np.ndarray):
                getattr(self.viewer.cam, key)[:] = value
            else:
                setattr(self.viewer.cam, key, value)