import argparse
import random
import torch
import numpy as np
import torch.optim as optim
import torch.distributions as dists
import wandb
import torch.nn.functional as F
import torch.nn as nn
from pathlib import Path
import math
from config import get_config
from networks import get_network
from datasets import load_data

# os.environ["WANDB_MODE"]="disabled"
wandb.init(project='Training', reinit=True)
parser = argparse.ArgumentParser()
parser.add_argument('--net', type=str, default='ResNet', choices=['SNN', 'IM', 'BNN', 'ResNet'], help='model used')
parser.add_argument('--dataset', type=str, default='CIFAR10', choices=['FashionMNIST', 'CIFAR10'], help='dataset used')
parser.add_argument('--smooth', type=bool, default=True, help='Set only to true for the experiments on the r-values')
parser.add_argument('--randseed', type=int, default=9999)
parser.add_argument('--device', default=0, type=int, help='If you have more than one gpu, select the one on which the code is run')
parser.add_argument('--stoch_varianz', default=0.05, type=float, help='Only applicable for SNN models - variance of noise added to the input')
parser.add_argument('--droprate', type=float, default=0.6, help='Only applicable for ResNet, specifies the dropout probability')
args = parser.parse_args()
args = get_config(args)
wandb.config.update(args)
args = get_config(args)
wandb.config.update(args)

torch.cuda.set_device(args.device)

# fix seeds
np.random.seed(args.randseed)
torch.manual_seed(args.randseed)
random.seed(args.randseed)

wandb.run.name = f'''{args.net}_{args.droprate}_{args.smooth}_{wandb.run.id}'''


def main(args):
    # get data
    train_loader, _, _ = load_data(args.dataset, args.batch_size, args.root_dir)

    # get model
    if args.net != 'ResNet':
        args.droprate = 0
    model = get_network(args)

    # train model
    for epoch in range(args.epochs):
        train_model(model, train_loader, epoch, args)

    # save model
    if args.smooth:
        torch.save(model.state_dict(), Path(args.root_dir,
                                            f'''models/{args.dataset}/model_smooth_{args.net}_{args.dataset}_{args.epochs}_{args.randseed}_{args.droprate}_{args.smooth_level}.bin'''))
    elif args.net == 'SNN':
        torch.save(model.state_dict(), Path(args.root_dir,
                                            f'''models/{args.dataset}/model_{args.net}_{args.dataset}_{args.epochs}_{args.randseed}_{args.layer}_{args.stoch_varianz}.bin'''))
    else:
        torch.save(model.state_dict(), Path(args.root_dir,
                                            f'''models/{args.dataset}/model_{args.net}_{args.dataset}_{args.epochs}_{args.randseed}_{args.droprate}.bin'''))


def learning_rate(init, epoch):
    '''Code from https://github.com/meliketoy/wide-resnet.pytorch
    MIT License

    Copyright (c) 2018 Bumsoo Kim

    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.
    '''
    optim_factor = 0
    if epoch > 160:
        optim_factor = 3
    elif epoch > 120:
        optim_factor = 2
    elif epoch > 60:
        optim_factor = 1
    return init * math.pow(0.2, optim_factor)


def get_loss(model, inputs, targets, args):
    if args.dataset == 'CIFAR10':
        criterion = nn.CrossEntropyLoss()
        outputs = model(inputs)
        predicted = torch.argmax(outputs, axis=1).detach().cpu().numpy()
        loss = criterion(outputs, targets)
    elif args.net == 'SNN':
        criterion = nn.CrossEntropyLoss()
        preds = []
        for _ in range(5):
            # 5 is the number of training samples we used to approximate the expectation
            y_s = model.forward(inputs)
            preds.append(F.softmax(y_s, dim=1))
        output = torch.mean(torch.stack(preds), 0)
        loss = criterion(output, targets)
        predicted = np.argmax(output.detach().cpu().numpy(), axis=1)
    else:
        log_p_y = []
        preds = []
        for _ in range(5):
            # 5 is the number of training samples we used to approximate the expectation
            y_s, D_KL = model.forward(inputs, True)
            preds.append(F.softmax(y_s, dim=1).detach().cpu().numpy())
            log_p_y_s = dists.Categorical(logits=y_s).log_prob(targets)
            log_p_y.append(log_p_y_s)
        if args.net == 'IM':
            E_nll = torch.mean(torch.logsumexp(torch.stack(log_p_y), 0) - math.log(5))
        elif args.net == 'BNN':
            E_nll = torch.mean(torch.stack(log_p_y))
        # lambda = 1 is equivalent to 1/60000
        loss = -E_nll + (1 / 60000 * D_KL)
        wandb.log({'E_NLL': -E_nll.item()})
        wandb.log({'KLD': D_KL.item()})
        predicted = np.argmax(np.mean(np.array(preds), axis=0), axis=1)

    return predicted, loss


def train_model(model, train_loader, epoch, args):
    model.train().cuda()
    correct = 0
    total = 0
    if args.dataset == 'CIFAR10':
        optimizer = optim.SGD(model.parameters(), lr=learning_rate(args.lr, epoch), momentum=0.9, weight_decay=5e-4)
        print('\n=> Training Epoch #%d, LR=%.4f,' % (epoch, learning_rate(args.lr, epoch)))
    else:
        optimizer = optim.Adam(model.parameters(), args.lr)

    for _, (inputs, targets) in enumerate(train_loader):
        inputs, targets = inputs.cuda(), targets.cuda()
        if args.smooth:
            # create noisy images
            inputs1 = torch.normal(mean=torch.zeros(inputs.shape),
                                   std=torch.ones(inputs.shape) * math.sqrt(args.smooth_level)).cuda() + inputs
            inputs2 = torch.normal(mean=torch.zeros(inputs.shape),
                                   std=torch.ones(inputs.shape) * math.sqrt(args.smooth_level)).cuda() + inputs
            inputs = torch.cat([inputs1, inputs2], dim=0)
            # clip noisy samples to valid input range
            inputs = torch.clip(inputs, 0, 1)
            targets = torch.cat([targets, targets], dim=0)
        optimizer.zero_grad()
        predicted, loss = get_loss(model, inputs, targets, args)
        loss.backward()
        wandb.log({f"loss": loss.item()})
        optimizer.step()  # Optimizer update
        total += targets.size(0)
        correct += np.equal(predicted, targets.detach().cpu().numpy()).sum()
    print('\n=> Training Epoch #%d,  Acc=%.2f,' % (epoch, (correct / total) * 100))


if __name__ == "__main__":
    main(args)
