# Walker2d-v2 env
# two objectives
# running speed, energy efficiency

import numpy as np
from gym import utils
from gym.envs.mujoco import mujoco_env
from os import path
from moenvs.MujocoEnvs.constraint_env import CMOEnv

class Walker2dEnv(mujoco_env.MujocoEnv, utils.EzPickle):
    def __init__(self):
        utils.EzPickle.__init__(self)
        mujoco_env.MujocoEnv.__init__(self, model_path = path.join(path.abspath(path.dirname(__file__)), "assets/walker2d.xml"), frame_skip = 4)
        self.obj_dim = 2 
        self.action_space_type = "Box"
        self.reward_space = np.zeros((self.obj_dim,))

    def step(self, a):
        qpos0_sum = np.sum(self.sim.data.qpos)
        qvel0_sum = np.sum(self.sim.data.qvel)
        posbefore = self.sim.data.qpos[0]
        # if isinstance(a, (np.ndarray)):
        #     a = a[0]
        a = np.clip(a, -1.0, 1.0)
        self.do_simulation(a, self.frame_skip)
        posafter, height, ang = self.sim.data.qpos[0:3]
        alive_bonus = 1.0
        reward_speed = (posafter - posbefore) / self.dt + alive_bonus
        reward_energy = 4.0 - 1.0 * np.square(a).sum() + alive_bonus
        done = not (height > 0.8 and height < 2.0 and
                    ang > -1.0 and ang < 1.0)
        ob = self._get_obs()

        x_velocity = (posafter - posbefore) / self.dt
        return ob, np.array([reward_speed, reward_energy],dtype=np.float32), done, {'x_velocity': x_velocity} 


    def _get_obs(self):
        qpos = self.sim.data.qpos
        qvel = self.sim.data.qvel
        return np.concatenate([qpos[1:], np.clip(qvel, -10, 10)]).ravel()

    def reset_model(self):
        # self.set_state(
        #     self.init_qpos
        #     + self.np_random.uniform(low=-0.005, high=0.005, size=self.model.nq),
        #     self.init_qvel
        #     + self.np_random.uniform(low=-0.005, high=0.005, size=self.model.nv),
        # )
        # return self._get_obs()
        c = 1e-3
        self.set_state(
            self.init_qpos + self.np_random.uniform(low=-c, high=c, size=self.model.nq),
            self.init_qvel + self.np_random.uniform(low=-c, high=c, size=self.model.nv)
        )
        return self._get_obs()

    def viewer_setup(self):
        self.viewer.cam.trackbodyid = 2
        self.viewer.cam.distance = self.model.stat.extent * 0.5
        self.viewer.cam.lookat[2] = 1.15
        self.viewer.cam.elevation = -20
    

class CMOWalker2dEnv(Walker2dEnv, CMOEnv):
    def __init__(self):
        CMOEnv.__init__(self, min_episode_cost=0.0, max_episode_cost=300.0, velocity_threshold=1.7075) 
        Walker2dEnv.__init__(self,)
        self.obj_dim = 3
        self.reward_space = np.zeros((self.obj_dim,))

    def step(self, a):
        ob, rew, _, info = super().step(a)
        x_velocity = info['x_velocity']
        cost = float(x_velocity > self.velocity_threshold)
        rew_vec = np.append(rew, cost)
        rew = rew_vec if self.linear_preference is None else np.dot(rew_vec[:len(self.linear_preference)], self.linear_preference)
        info.update({'cost': cost, 'rew_vec': rew_vec[:-1]})
        done = not self.is_healthy
        return ob, rew, False, info
    
    @property
    def is_healthy(self):
        z, angle = self.data.qpos[1:3]

        min_z, max_z = (0.8, 2.0)
        min_angle, max_angle = (-1.0, 1.0)

        healthy_z = min_z < z < max_z
        healthy_angle = min_angle < angle < max_angle
        is_healthy = healthy_z and healthy_angle

        return is_healthy