import numpy as np
from rand_param_envs.base import RandomEnv
from rand_param_envs.gym import utils

class AntGoalRandParamsEnv(RandomEnv, utils.EzPickle):
    def __init__(self, log_scale_limit=3.0):
        self._goal_pos = np.array([0, 2.])
        RandomEnv.__init__(self, log_scale_limit, 'low_gear_ratio_ant.xml', 5)
        utils.EzPickle.__init__(self)

    def _step(self, action):
        self.do_simulation(action, self.frame_skip)
        xposafter = np.array(self.get_body_com("torso"))

        dist = np.linalg.norm(xposafter[:2] - self._goal_pos)
        goal_reward = -np.sum(
            np.abs(xposafter[:2] - self._goal_pos)
        ) + 4.0  # make it happy, not suicidal

        lb, ub = self.action_bounds
        scaling = (ub - lb) * 0.5
        ctrl_cost = 0.5 * 1e-2 * np.square(action / scaling).sum()
        contact_cost = (
            0.5 * 1e-3 * np.sum(np.square(np.clip(self.data.cfrc_ext, -1, 1)))
        )
        survive_reward = 0.05
        reward = goal_reward - ctrl_cost - contact_cost + survive_reward
        # reward = goal_reward
        state = self.state_vector()
        notdone = np.isfinite(state).all() and state[2] >= 0.2 and state[2] <= 1.0
        done = not notdone
        # done = False
        sparse_goal_reward = goal_reward
        if dist > 0.8:
            sparse_goal_reward = -np.sum(np.abs(self._goal_pos)) + 4.0
        sparse_reward = sparse_goal_reward - ctrl_cost - contact_cost + survive_reward
        reward = sparse_reward
        ob = self._get_obs()
        return (
            ob,
            reward,
            done,
            dict(
                sparse_reward=sparse_reward,
                goal_forward=goal_reward,
                reward_ctrl=-ctrl_cost,
                reward_contact=-contact_cost,
                reward_survive=survive_reward,
                xposafter=xposafter,
                done=done,
            ),
        )

    def _get_obs(self):
        return np.concatenate(
            [
                self.data.qpos.flat,
                self.data.qvel.flat,
                np.clip(self.data.cfrc_ext, -1, 1).flat,
            ]
        )

    def reset_model(self):
        qpos = self.init_qpos + self.np_random.uniform(size=self.model.nq, low=-.1, high=.1)
        qvel = self.init_qvel + self.np_random.randn(self.model.nv) * .1
        self.set_state(qpos, qvel)
        return self._get_obs()

    def viewer_setup(self):
        self.viewer.cam.distance = self.model.stat.extent * 0.5

    @property
    def action_bounds(self):
        bounds = self.model.actuator_ctrlrange.copy().astype(np.float32)
        return bounds.T

'''
if __name__ == "__main__":

    env = Walker2DRandParamsEnv()
    tasks = env.sample_tasks(40)
    while True:
        env.reset()
        env.set_task(np.random.choice(tasks))
        print(env.model.body_mass)
        for _ in range(100):
            env.render()
            env.step(env.action_space.sample())  # take a random action
'''

