import warnings
import time
import numpy as np
import argparse
import seaborn as sns
from torch_geometric.utils import dropout_adj, add_self_loops
import torch

from models import *
from utils import set_seed, random_splits
from dataset_loader import DataLoader
from eval import unsupervised_test_linear
from unsup_model import CCA_SSG
warnings.filterwarnings("ignore")


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--seed', type=int, default=42, help='seed.')
    parser.add_argument('--dataset', type=str,default='Cora')
    parser.add_argument('--device', type=int, default=0, help='GPU device.')
    parser.add_argument('--runs', type=int, default=10, help='number of runs.')
    parser.add_argument('--net', type=str, default='GCN')

    parser.add_argument('--num_layers', type=int, default=2)
    parser.add_argument('--hidden', type=int, default=64, help='hidden units.')
    parser.add_argument('--dropout', type=float, default=0.5, help='dropout for neural networks.')
    
    parser.add_argument('--fix_split', action='store_true')
    parser.add_argument('--train_rate', type=float, default=0.6, help='train set rate.')
    parser.add_argument('--val_rate', type=float, default=0.2, help='val set rate.')

    # unsupervised learning
    parser.add_argument('--lambd', type=float, default=1e-3, help='trade-off ratio.')
    parser.add_argument('--de1', default=0.2, type=float)
    parser.add_argument('--de2', default=0.2, type=float)
    parser.add_argument('--df1', default=0.2, type=float)
    parser.add_argument('--df2', default=0.2, type=float)

    parser.add_argument("--patience", type=int, default=20, help="Patient epochs to wait before early stopping.")
    parser.add_argument("--unsup_epochs", type=int, default=500, help="Unupservised training epochs.")
    parser.add_argument("--lr1", type=float, default=0.001, help="Learning rate of the unsupervised model.")
    parser.add_argument("--lr2", type=float, default=0.01, help="Learning rate of linear evaluator.")
    parser.add_argument("--wd1", type=float, default=0.0, help="Weight decay of the unsupervised model.")
    parser.add_argument("--wd2", type=float, default=0.0, help="Weight decay of linear evaluator.")
    args = parser.parse_args()
    return args


def drop_features(x, drop_prob):
    drop_mask = torch.empty((x.size(1), ), dtype=torch.float32, device=x.device).uniform_(0, 1) < drop_prob
    x = x.clone()
    x[:, drop_mask] = 0
    return x


def random_aug(edge_index, x, df, de):
    x = drop_features(x, df)
    edge_index = dropout_adj(edge_index, p=de)[0]
    return edge_index, x


def unsupervised_learning(data, args, device):
    best = float("inf")
    unsup_tag = str(int(time.time()))

    for epoch in range(args.unsup_epochs):
        model.train()
        optimizer.zero_grad()

        edge_index1, feat1 = random_aug(data.edge_index, data.x, args.df1, args.de1)
        edge_index2, feat2 = random_aug(data.edge_index, data.x, args.df2, args.de2)

        edge_index1 = add_self_loops(edge_index1)[0]
        edge_index2 = add_self_loops(edge_index2)[0]

        z1, z2 = model(feat1, edge_index1, feat2, edge_index2)

        c = torch.mm(z1.T, z2) / data.num_nodes
        c1 = torch.mm(z1.T, z1) / data.num_nodes
        c2 = torch.mm(z2.T, z2) / data.num_nodes

        loss_inv = -torch.diagonal(c).sum()
        iden = torch.tensor(np.eye(c.size(0))).to(device)
        loss_dec1 = (iden - c1).pow(2).sum()
        loss_dec2 = (iden - c2).pow(2).sum()

        loss = loss_inv + args.lambd * (loss_dec1 + loss_dec2)

        loss.backward()
        optimizer.step()

        if loss < best:
            best = loss
            torch.save(model.state_dict(), 'unsup_pkl/' + 'cca_ssg_cl_' + args.net + '_best_model_'+ args.dataset + unsup_tag + '.pkl')

    model.load_state_dict(torch.load('unsup_pkl/' + 'cca_ssg_cl_' + args.net + '_best_model_'+ args.dataset + unsup_tag + '.pkl'))
    model.eval()
    embeds = model.get_embeddings(data.x, data.edge_index)
    return embeds


if __name__ == '__main__':
    args = parse_args()
    print(args)
    print("---------------------------------------------")
    
    set_seed(args.seed)
    #10 fixed seeds for random splits from BernNet
    SEEDS=[1941488137,4198936517,983997847,4023022221,4019585660,2108550661,1648766618,629014539,3212139042,2424918363]
    device = torch.device('cuda:'+str(args.device) if torch.cuda.is_available() else 'cpu')

    dataset = DataLoader(args.dataset)
    data = dataset[0]
    data = data.to(device)

    percls_trn = int(round(args.train_rate * len(data.y) / dataset.num_classes))
    val_lb = int(round(args.val_rate * len(data.y)))
    
    encoder = UnsupGCN_Net(dataset=dataset, args=args)
    model = CCA_SSG(encoder=encoder).to(args.device)
    optimizer = torch.optim.Adam(model.parameters(), lr=args.lr1, weight_decay=args.wd1)
    embeds = unsupervised_learning(data=data, args=args, device=device)
 
    if args.dataset not in ['Computers', 'Photo']:
        full_train_mask, full_val_mask, full_test_mask = data.train_mask, data.val_mask, data.test_mask

    unsup_results = []
    for RP in range(args.runs):
        args.seed = SEEDS[RP]
        
        if args.fix_split:
            if args.dataset in ['Computers', 'Photo']:  # no public splitting, train/val/test=1/1/8
                percls_trn = int(round(0.1 * len(data.y) / dataset.num_classes))
                val_lb = int(round(0.1 * len(data.y)))
                data = random_splits(data, dataset.num_classes, percls_trn, val_lb, args.seed).to(device)
            else:
                data.train_mask, data.val_mask, data.test_mask = full_train_mask[:, RP], full_val_mask[:, RP], full_test_mask[:, RP]
        else:
            data = random_splits(data, dataset.num_classes, percls_trn, val_lb, args.seed).to(device)

        eval_acc = unsupervised_test_linear(data=data, embeds=embeds, n_classes=dataset.num_classes, device=device, args=args)
        unsup_results.append(eval_acc)

    test_acc_mean = np.mean(unsup_results) * 100
    values = np.asarray(unsup_results, dtype=object)
    uncertainty = np.max(np.abs(sns.utils.ci(sns.algorithms.bootstrap(values, func=np.mean, n_boot=1000), 95) - values.mean()))
    print(f'test acc mean = {test_acc_mean:.4f} ± {uncertainty * 100:.4f}')



