"""
MIT License

Copyright (c) 2022 Author(s)

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.
"""

import datetime
import numpy as np
import tensorflow as tf

from models.optimizers import OptimizerManager
from models.backbones import SmallModel
from utils.misc import set_gpu_devices, fix_random_seed,\
    concat_configs, concat_configs,\
    set_gpu_devices
from utils.utiltensorboard import TensorboardLogger
from utils.utilckpt import checkpoint_logger
from dataprocess.dataloader import load_mnist
from algorithm.alg import AngularUpdate, calc_perp_para_translation

# Load config
yaml_paths = [
    "./configs/config_mnist.yaml",
    "./configs/info_mnist.yaml",
    "./configs/info_available_list.yaml",]
config = concat_configs(paths=yaml_paths)
config["comment"] += "ModGrad{}{}LR{}WD{}".format(
    config["flag_modgrad"], config["prefac_xi"],
    config["learning_rate"], config["param_wd"])

# GPU
set_gpu_devices(config["gpu"])

# Global
PREPROC = lambda x: x/127.5 - 1
NOW = datetime.datetime.now().strftime("%Y%m%d_%H%M%S%f")[:-3]

# Set Random Seeds (Optional)
fix_random_seed(flag_seed=config["flag_seed"], seed=config["seed"])

# Model
tf.keras.backend.set_floatx("float64")
model = SmallModel(num_classes=config["num_classes"], units=config["units"])

# Dataset
dstr = load_mnist(preproc=PREPROC, batch_size=config["num_trdata"], data_dir=config["data_dir"])

# Optimizer
kwargs_scheduler = {
    "learning_rate": config["learning_rate"]}
kwargs_optimizer = {
    "momentum": 0.0, 
    "nesterov": False,}

opt_manager = OptimizerManager(name_scheduler="Constant",
    name_optimizer="SGD",
    kwargs_scheduler=kwargs_scheduler,
    kwargs_optimizer=kwargs_optimizer)
optimizer = opt_manager()
scheduler = opt_manager.scheduler

# TensorBoard
tblogger = TensorboardLogger(
    root_tblogs=config["root_tblogs"], 
    subproject_name=config["subproject_name"], 
    exp_phase=config["exp_phase"], 
    comment=config["comment"], 
    time_stamp=NOW)

# Checkpoint
global_step = tf.Variable(0, name="global_step", dtype=tf.int64)
_, ckpt_manager = checkpoint_logger(
    global_step, 
    model, 
    optimizer, 
    False, # flag_resume
    config["root_ckptlogs"], 
    config["subproject_name"], 
    config["exp_phase"],
    config["comment"], 
    NOW,
    "", 
    None) # max_to_keep


# Training
#=================================================
# Initialize
angupd = AngularUpdate(model)
with tblogger.writer.as_default():
    for epoch in range(config["num_iter"]):
        for cnt, (x, y) in enumerate(dstr):
            # Build
            if int(global_step) == 0:
                x = tf.reshape(x, (-1,784))
                model.build(input_shape=x.shape)
                model.summary()

            # Save model
            if (int(global_step) == 0) or (int(global_step) % config["save_steps"] == 0):
                ckpt_manager._checkpoint_prefix = \
                    ckpt_manager._checkpoint_prefix[:ckpt_manager.\
                        _checkpoint_prefix.rfind("/") + 1] + \
                    "ckpt_step{}".format(
                        int(global_step))
                save_path_prefix = ckpt_manager.save()
                print("Saved checkpoint for step {}: {}".format(
                    int(global_step), save_path_prefix))

            # Forward propagation
            with tf.GradientTape(persistent=True) as tape1:
                with tf.GradientTape() as tape0:
                    x = tf.reshape(x, (-1,784))
                    logits, bottleneck_feat = model(x, training=False)
                        # (batch, num_classes) and (batch, final_size)
                    xent = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
                        labels=y, logits=logits))
                    total_loss = xent
                    for variables in model.trainable_variables:
                        total_loss += config["param_wd"] * tf.nn.l2_loss(variables)

                gradients = tape0.gradient(total_loss, model.trainable_variables)
                    # [(n-dim weight shape,)] * num of trainable layers
                normsq = [tf.norm(v)**2 for v in gradients]
                    # [scalar Tensor] * num of trainable layers

            # Calc counter term
            if config["flag_modgrad"]:
                tbx0 = [0.25 * v for v in tape1.gradient(normsq, model.trainable_variables)]
                eta_tbx0 = [config["prefac_xi"] * v for v in tbx0]
                modgrads = [v + w for v, w in zip(gradients, eta_tbx0)]
            else:
                modgrads = gradients

            # Apply gradients
            angupd.keep_weights()
            optimizer.apply_gradients(
                zip(modgrads, model.trainable_variables))
            global_step.assign_add(1)

            # Plot
            if (int(global_step) == 1) or (int(global_step)%10 == 0):
                noe_sum = tf.reduce_sum(model.trainable_variables[2])
                noe_r = tf.norm(model.trainable_variables[1])
                angular_update = angupd(return_angle=False)[1]
                angular_update_th = tf.cos(tf.sqrt(tf.cast(2*config["learning_rate"]*config["param_wd"], 
                                    tf.float64))).numpy()
                angular_update_log = - tf.math.log(tf.clip_by_value(1. - angular_update, 0., 2.))
                angular_update_log_th = - tf.math.log(tf.clip_by_value(1. - angular_update_th, 0., 2.))
                thperp, thpara = calc_perp_para_translation(model.trainable_variables[2])
                norm_thperp = tf.norm(thperp)
                norm_thpara = tf.norm(thpara)

                tblogger.scalar_summary("Losses/Total loss", 
                    total_loss, int(global_step))
                tblogger.scalar_summary("Losses/Xentropy loss", 
                    xent, int(global_step))
                tblogger.scalar_summary("Losses/Weight decay", 
                    tf.reduce_sum([tf.nn.l2_loss(v) for v in model.trainable_variables]), 
                    int(global_step))
                tblogger.scalar_summary("Dynamics/Dense2/Sum", 
                    noe_sum, int(global_step))
                tblogger.scalar_summary("Dynamics/Dense1Radius", 
                    noe_r, int(global_step))
                tblogger.scalar_summary("Dynamics/Dense1GradNorm", 
                    tf.sqrt(normsq[1]), int(global_step))
                tblogger.scalar_summary("Dynamics/Dense1/Cos(angular update)", 
                    angular_update, int(global_step), 
                    description="LR={},WD={},Equil: {}".format(
                        config["learning_rate"], config["param_wd"], angular_update_th))
                tblogger.scalar_summary("Dynamics/Dense1/-log(1-cos(ang upd))", 
                    angular_update_log, int(global_step), 
                    description="LR={},WD={},Equil: {}".format(
                        config["learning_rate"], config["param_wd"], angular_update_log_th))
                tblogger.scalar_summary("Dynamics/Dense2/NormThperp", 
                    norm_thperp , int(global_step))
                tblogger.scalar_summary("Dynamics/Dense2/NormThpara", 
                    norm_thpara , int(global_step))
            
            # Verbose
            if (int(global_step) == 1) or (int(global_step) % config["verbose_steps"] == 0):
                print("Global step:   ", int(global_step), "/", config["num_iter"])
                print("Total loss:    ", total_loss.numpy())
                print("Radius:        ", noe_r.numpy())
                print("GradNorm:      ", tf.reduce_sum([tf.sqrt(v) for v in normsq]).numpy())
                print("AngUpd:        ", angular_update.numpy())
                print("AngUpd (equil):", angular_update_th)