# coding=utf-8
# Copyright 2019 The Weak Disentangle 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.
"""
python -m scripts.train_disentangled_model --train-data-path path/to/train_dataset.npz --eval-data-path path/to/eval_dataset.npz --factors r=0,1,2,3
"""
import click
import gin
import matplotlib.pyplot as plt
import numpy as np
import os
import tensorflow as tf
import time
from absl import app
from tensorflow import gfile
from tqdm import tqdm

from weakly_supervised_control.disentanglement.train_utils import (
    load_dset, DisentanglementModel, DisentanglementTrainer)
tf.enable_v2_behavior()
tfk = tf.keras


@click.command()
@click.option('--train-data-path',
              '-i',
              default=None,
              type=str,
              help="Directory to load the training dataset from.")
@click.option('--eval-data-path',
              '-i',
              default=None,
              type=str,
              help="Directory to load the training dataset from.")
@click.option('--output',
              '-o',
              type=str,
              default='/tmp/weakly_supervised_control/disentangled_model',
              help="Output directory")
@click.option('--factors', default="r=0,1,2,3", type=str)
@click.option('--batch-size', default=64, type=int)
@click.option('--iterations', default=1e5, type=int)
@click.option('--iter-log', default=1000, type=int)
@click.option('--iter-save', default=10000, type=int)
def main(train_data_path: str,
         eval_data_path: str,
         output: str,
         factors: str,
         batch_size: int,
         iterations: int,
         iter_log: int, iter_save: int):
    output += '/' + '{}-{}-{}'.format(
        os.path.basename(train_data_path).split('.')[0],
        factors,
        time.strftime("%Y%m%d-%H%M%S"))
    ckptdir = os.path.join(output, "ckptdir")
    vizdir = os.path.join(output, "vizdir")
    ckpt_prefix = os.path.join(ckptdir, "model")

    # Create output directories.
    gfile.MakeDirs(ckptdir)
    gfile.MakeDirs(vizdir)

    # Initialize dataset, model, and trainer.
    if eval_data_path is None:
        eval_data_path = train_data_path
    dset = load_dset(train_data_path)
    eval_dset = load_dset(eval_data_path)
    model = DisentanglementModel(dset, factors)
    trainer = DisentanglementTrainer(model, dset, batch_size=batch_size)

    summary_writer = tf.contrib.summary.create_file_writer(
        os.path.join(output, 'tb'), max_queue=1)

    def write_summary(d: dict, step: int, scalar_prefix: str = ""):
        with summary_writer.as_default():
            for k, v in d.items():
                tf.compat.v2.summary.scalar(scalar_prefix + k, v, step=step)
        summary_writer.flush()

    # Load model from checkpoint.
    save_counter = model.load_checkpoint(ckptdir)
    train_range = range(iter_save * int(save_counter - 1), iterations)

    total_train_time = 0
    start_time = time.time()
    for global_step in train_range:
        losses, train_time = trainer.train_batch()
        total_train_time += train_time

        # Generic bookkeeping
        if (global_step + 1) % iter_log == 0 or global_step == 0:
            write_summary(losses, global_step, 'train/')

            elapsed_time = time.time() - start_time
            write_summary({
                'elapsed_time': elapsed_time,
                'elapsed_time_iter_s': global_step / elapsed_time,
                'train_time_iter_s': global_step / total_train_time
            }, global_step, 'time/')

            string = ", ".join((
                "Iter: {:07d}, Elapsed: {:.3e}, (Elapsed) Iter/s: {:.3e}, (Train Step) Iter/s: {:.3e}".format(
                    global_step, elapsed_time, global_step / elapsed_time, global_step / total_train_time),
                "Gen: {gen_loss:.4f}, Dis: {dis_loss:.4f}, Enc: {enc_loss:.4f}".format(
                    **losses)
            )) + "."
            print(string)

        # Log visualizations and evaluations
        if (global_step + 1) % iter_save == 0 or global_step == 0:
            evals = model.evaluate_correlation(eval_dset)
            write_summary(evals, global_step, "eval/")

        # Save model only after ensuring all measurements are taken.
        # This ensures that restarts always computes the evals
        if (global_step + 1) % iter_save == 0 or global_step == 0:
            model.save_checkpoint(ckpt_prefix)


if __name__ == "__main__":
    main()
