import torch
import torch.nn as nn
from torchvision.models import resnet18
import torch.nn.functional as F

from src.utils import utils

class mnist_conv(nn.Module):
    def __init__(self, sparsity):
        super(mnist_conv, self).__init__()
        self.act_fn = nn.ReLU()
        self.conv = torch.nn.Conv2d
        self.linear = torch.nn.Linear

        self.layers1 = nn.Sequential(
            self.conv(1, 64, 5),
            nn.MaxPool2d(2),
            self.act_fn,
            self.conv(64, 64, 5),
            nn.MaxPool2d(2),
            self.act_fn,
            nn.Flatten()
        )

        self.layers2 = nn.Sequential(
            self.linear(4 * 4 * 64, 128),
            self.act_fn,
            self.linear(128, 10)
        )

        # Apply sparse initialization
        for param in self.parameters():
            utils.initialize_sparse_tensor(param, sparsity=sparsity)

    def forward(self, x):
        x = self.layers1(x)
        x = self.layers2(x)
        return x

class CIFAR10_ResNet(nn.Module):
    def __init__(self, num_classes=10, sparsity=0.9):
        super(CIFAR10_ResNet, self).__init__()
        self.model = resnet18(weights=None)  # Load ResNet-18 without pretrained weights
        self.model.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)  # Modify for 32x32 input
        self.model.fc = nn.Linear(512, num_classes)  # Change final layer for CIFAR-10

        # Apply sparse initialization
        # for param in self.parameters():
        #     utils.initialize_sparse_tensor(param, sparsity=sparsity)

    def forward(self, x):
        return self.model(x)
    
#%% VGG

cfg = {
    'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
    'VGG19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}


class VGG(nn.Module):
    def __init__(self, vgg_name):
        super(VGG, self).__init__()
        self.features = self._make_layers(cfg[vgg_name])
        self.classifier = nn.Linear(512, 10)

    def forward(self, x):
        out = self.features(x)
        out = out.view(out.size(0), -1)
        out = self.classifier(out)
        return out

    def _make_layers(self, cfg):
        layers = []
        in_channels = 3
        for x in cfg:
            if x == 'M':
                layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
            else:
                layers += [nn.Conv2d(in_channels, x, kernel_size=3, padding=1),
                           nn.BatchNorm2d(x),
                           nn.ReLU(inplace=True)]
                in_channels = x
        layers += [nn.AvgPool2d(kernel_size=1, stride=1)]
        return nn.Sequential(*layers)
    

#%% ResNet
class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, in_planes, planes, stride=1):
        super(BasicBlock, self).__init__()
        self.conv1 = nn.Conv2d(
            in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
                               stride=1, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes)

        self.shortcut = nn.Sequential()
        if stride != 1 or in_planes != self.expansion*planes:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_planes, self.expansion*planes,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(self.expansion*planes)
            )

    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        out += self.shortcut(x)
        out = F.relu(out)
        return out


class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, in_planes, planes, stride=1):
        super(Bottleneck, self).__init__()
        self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
                               stride=stride, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = nn.Conv2d(planes, self.expansion *
                               planes, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm2d(self.expansion*planes)

        self.shortcut = nn.Sequential()
        if stride != 1 or in_planes != self.expansion*planes:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_planes, self.expansion*planes,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(self.expansion*planes)
            )

    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = F.relu(self.bn2(self.conv2(out)))
        out = self.bn3(self.conv3(out))
        out += self.shortcut(x)
        out = F.relu(out)
        return out


class ResNet(nn.Module):
    def __init__(self, block, num_blocks, num_classes=10):
        super(ResNet, self).__init__()
        self.in_planes = 64

        self.conv1 = nn.Conv2d(3, 64, kernel_size=3,
                               stride=1, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
        self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
        self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)
        self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)
        self.linear = nn.Linear(512*block.expansion, num_classes)

    def _make_layer(self, block, planes, num_blocks, stride):
        strides = [stride] + [1]*(num_blocks-1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_planes, planes, stride))
            self.in_planes = planes * block.expansion
        return nn.Sequential(*layers)

    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.layer4(out)
        out = F.adaptive_avg_pool2d(out, (1, 1))  # ensures output is always 512 x 1 x 1
        out = out.view(out.size(0), -1)
        out = self.linear(out)
        return out


def ResNet18():
    return ResNet(BasicBlock, [2, 2, 2, 2])


def ResNet34():
    return ResNet(BasicBlock, [3, 4, 6, 3])


def ResNet50():
    return ResNet(Bottleneck, [3, 4, 6, 3])

def ResNet101():
    return ResNet(Bottleneck, [3, 4, 23, 3])

def ResNet152():
    return ResNet(Bottleneck, [3, 8, 36, 3])


## Wide ResNet
class WideResNet(nn.Module):
    def __init__(self, depth=28, widen_factor=10, num_classes=10):
        super(WideResNet, self).__init__()
        assert (depth - 4) % 6 == 0, "Depth should be 6n+4"
        n = (depth - 4) // 6
        k = widen_factor
        nStages = [16, 16*k, 32*k, 64*k]

        self.conv1 = nn.Conv2d(3, nStages[0], kernel_size=3, stride=1, padding=1, bias=False)
        self.layer1 = self._wide_layer(nStages[0], nStages[1], n, stride=1)
        self.layer2 = self._wide_layer(nStages[1], nStages[2], n, stride=2)
        self.layer3 = self._wide_layer(nStages[2], nStages[3], n, stride=2)
        self.bn1 = nn.BatchNorm2d(nStages[3])
        self.linear = nn.Linear(nStages[3], num_classes)

    def _wide_layer(self, in_planes, out_planes, num_blocks, stride):
        strides = [stride] + [1]*(num_blocks-1)
        layers = []
        for s in strides:
            layers.append(BasicBlock(in_planes, out_planes, s))
            in_planes = out_planes
        return nn.Sequential(*layers)

    def forward(self, x):
        out = self.conv1(x)
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = F.relu(self.bn1(out))
        out = F.adaptive_avg_pool2d(out, 1)
        out = torch.flatten(out, 1)  # same as view(batch, -1)
        return self.linear(out)


def get_model(conf, state_dict=None):
    model_name = conf.model
    dataset = conf.dataset
    if model_name == 'ResNet18-CIFAR10':
        model = CIFAR10_ResNet(sparsity=conf.model_init_sparsity)
    elif model_name == 'VGG16':
        model = VGG('VGG16')
    elif model_name == 'ResNet18' and dataset == 'CIFAR10':
        model = ResNet18()
    elif model_name == 'ResNet18' and dataset == 'Tiny ImageNet':
        model = ResNet(BasicBlock, [2, 2, 2, 2], num_classes=200)
    elif model_name == 'WideResNet-28-10' and dataset == 'CIFAR10':
        model =  WideResNet(depth=28, widen_factor=10, num_classes=10)
    elif model_name == 'WideResNet-28-10' and dataset == 'Tiny ImageNet':
        model =  WideResNet(depth=28, widen_factor=10, num_classes=200)
    
    # Whether laoding from checkpoint or creating a new sparse model
    if state_dict:
        model.load_state_dict(state_dict)
    else:
        model = utils.init_weights(conf, model) # Sparse initialisation
    return model