import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import sys
import os

from advtr.data import train_loader, test_loader
from advtr.attacks import fgsm, rfgsm, pgd, rpgd, pgd2, rpgd2, pgd_linf, rpgd_linf
from advtr.train import epoch, epoch_adversarial
from advtr.model import model_gen


net, eps, alpha, seed = sys.argv[1], float(sys.argv[2]), float(sys.argv[3]), int(sys.argv[4])

torch.manual_seed(seed)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model_file = "./results/models/model_standard_net=%s_eps=%s_alpha=%s_seed=%s.pt"%(net,eps,alpha,seed)
stats_file = "./results/stats/stats_standard_net=%s_eps=%s_alpha=%s_seed=%s.pt"%(net,eps,alpha,seed)

if not os.path.exists('./results/models'):
    os.makedirs('./results/models')
if not os.path.exists('./results/stats'):
    os.makedirs('./results/stats')

model = model_gen(net).to(device)

opt = optim.SGD(model.parameters(), lr=1)

stats= []
if not os.path.exists(model_file):
    for t in range(20):
        train_err, train_loss = epoch(train_loader, model, opt)
        test_err, test_loss = epoch(test_loader, model)

        adv_err_fgsm, _ = epoch_adversarial(test_loader, model, fgsm, epsilon=eps)
        adv_err_pgd, _ = epoch_adversarial(test_loader, model, pgd, epsilon=eps, alpha=alpha)
        adv_err_pgd2, _ = epoch_adversarial(test_loader, model, pgd2, epsilon=eps, alpha=alpha)
        adv_err_pgd_linf, _ = epoch_adversarial(test_loader, model, pgd_linf, epsilon=eps, alpha=alpha)
        adv_err_rfgsm, _ = epoch_adversarial(test_loader, model, rfgsm, epsilon=eps)
        adv_err_rpgd, _ = epoch_adversarial(test_loader, model, rpgd, epsilon=eps, alpha=alpha)
        adv_err_rpgd2, _ = epoch_adversarial(test_loader, model, rpgd2, epsilon=eps, alpha=alpha)
        adv_err_rpgd_linf, _ = epoch_adversarial(test_loader, model, rpgd_linf, epsilon=eps, alpha=alpha)

        stats.append([train_err, train_loss, test_err, test_loss, adv_err_fgsm, adv_err_pgd, adv_err_pgd2, adv_err_pgd_linf, adv_err_rfgsm, adv_err_rpgd, adv_err_rpgd2, adv_err_rpgd_linf])

        if t % 5 == 4:
            for param_group in opt.param_groups: param_group["lr"] /= 5

        print(*("{:.6f}".format(i) for i in (train_err, test_err, adv_err_fgsm, adv_err_rfgsm, adv_err_pgd, adv_err_rpgd, adv_err_pgd2, adv_err_rpgd2, adv_err_pgd_linf, adv_err_rpgd_linf)), sep="\t")

    torch.save(stats, stats_file)
    torch.save(model.state_dict(), model_file)
