# Copyright 2022 The Brax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Soft Actor-Critic training.

See: https://arxiv.org/pdf/1812.05905.pdf
"""

import os
import time
from typing import Any, Callable, Dict, Mapping, Optional, Tuple

from absl import logging
from brax import envs
from brax.io import model
from brax.training import distribution
from brax.training import networks
from brax.training import normalization
from brax.training import pmap
from brax.training.types import Params
from brax.training.types import PRNGKey
import flax
from flax import linen
import jax
import jax.numpy as jnp
import numpy as onp
import optax

Metrics = Mapping[str, jnp.ndarray]


@flax.struct.dataclass
class Transition:
  """Contains data for one environment step."""
  o_tm1: jnp.ndarray
  a_tm1: jnp.ndarray
  r_t: jnp.ndarray
  o_t: jnp.ndarray
  d_t: jnp.ndarray  # discount (1-done)
  truncation_t: jnp.ndarray


# The rewarder allows to change the reward of before the learner trains.
RewarderState = Any
RewarderInit = Callable[[int, PRNGKey], RewarderState]
ComputeReward = Callable[[RewarderState, Transition, PRNGKey],
                         Tuple[RewarderState, jnp.ndarray, Metrics]]
Rewarder = Tuple[RewarderInit, ComputeReward]


@flax.struct.dataclass
class ReplayBuffer:
  """Contains data related to a replay buffer."""
  data: jnp.ndarray
  current_position: jnp.ndarray
  current_size: jnp.ndarray


@flax.struct.dataclass
class TrainingState:
  """Contains training state for the learner."""
  policy_optimizer_state: optax.OptState
  policy_params: Params
  q_optimizer_state: optax.OptState
  q_params: Params
  target_q_params: Params
  key: PRNGKey
  steps: jnp.ndarray
  alpha_optimizer_state: optax.OptState
  alpha_params: Params
  normalizer_params: Params
  # The is passed to the rewarder to update the reward.
  rewarder_state: Any


def make_sac_networks(
    param_size: int,
    obs_size: int,
    action_size: int,
    hidden_layer_sizes: Tuple[int, ...] = (256, 256),
) -> Tuple[networks.FeedForwardModel, networks.FeedForwardModel]:
  """Creates a policy and a value networks for SAC."""
  policy_module = networks.MLP(
      layer_sizes=hidden_layer_sizes + (param_size,),
      activation=linen.relu,
      kernel_init=jax.nn.initializers.lecun_uniform())

  class QModule(linen.Module):
    """Q Module."""
    n_critics: int = 2

    @linen.compact
    def __call__(self, obs: jnp.ndarray, actions: jnp.ndarray):
      hidden = jnp.concatenate([obs, actions], axis=-1)
      res = []
      for _ in range(self.n_critics):
        q = networks.MLP(
            layer_sizes=hidden_layer_sizes + (1,),
            activation=linen.relu,
            kernel_init=jax.nn.initializers.lecun_uniform())(
                hidden)
        res.append(q)
      return jnp.concatenate(res, axis=-1)

  q_module = QModule()

  dummy_obs = jnp.zeros((1, obs_size))
  dummy_action = jnp.zeros((1, action_size))
  policy = networks.FeedForwardModel(
      init=lambda key: policy_module.init(key, dummy_obs),
      apply=policy_module.apply)
  value = networks.FeedForwardModel(
      init=lambda key: q_module.init(key, dummy_obs, dummy_action),
      apply=q_module.apply)
  return policy, value


def train(
    environment_fn: Callable[..., envs.Env],
    num_timesteps,
    episode_length: int,
    action_repeat: int = 1,
    num_envs: int = 1,
    num_eval_envs: int = 128,
    learning_rate: float = 1e-4,
    discounting: float = 0.9,
    seed: int = 0,
    batch_size: int = 256,
    log_frequency: int = 10000,
    normalize_observations: bool = False,
    max_devices_per_host: Optional[int] = None,
    reward_scaling: float = 1.,
    tau: float = 0.005,
    min_replay_size: int = 8192,
    max_replay_size: int = 1048576,
    grad_updates_per_step: float = 1,
    progress_fn: Optional[Callable[[int, Dict[str, Any]], None]] = None,
    # The rewarder is an init function and a compute_reward function.
    # It is used to change the reward before the learner trains on it.
    make_rewarder: Optional[Callable[[], Rewarder]] = None,
    checkpoint_dir: Optional[str] = None):
  """SAC training."""
  assert min_replay_size % num_envs == 0
  assert max_replay_size % min_replay_size == 0
  # jax.config.update('jax_log_compiles', True)

  process_count = jax.process_count()
  process_id = jax.process_index()
  local_device_count = jax.local_device_count()
  local_devices_to_use = local_device_count
  if max_devices_per_host:
    local_devices_to_use = min(local_devices_to_use, max_devices_per_host)
  logging.info(
      'Device count: %d, process count: %d (id %d), local device count: %d, '
      'devices to be used count: %d', jax.device_count(), process_count,
      process_id, local_device_count, local_devices_to_use)