#!/usr/bin/env python3
import torch
from torch import nn
from torch.nn import functional as F
from torchvision import models

def conv3x3(in_planes, out_planes, stride=1):
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)

class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, in_planes, planes, stride=1):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(in_planes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = conv3x3(planes, planes)
        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 = out + self.shortcut(x)
        out = F.relu(out)
        return out

class ResNet(nn.Module):
    def __init__(self, num_classes=1, nf=20, input_size=(3, 32, 32), pretrained=True):
        super(ResNet, self).__init__()
        self.in_planes = nf
        self.input_size = input_size

        # Load pretrained resnet18 from torchvision
        if pretrained:
            resnet = models.resnet18(pretrained=True)
        else:
            resnet = models.resnet18(pretrained=False)

        # Modify the first conv layer to fit the input size
        resnet.conv1 = nn.Conv2d(input_size[0], nf, kernel_size=3, stride=1, padding=1, bias=False)
        resnet.bn1 = nn.BatchNorm2d(nf)

        # Replace resnet layers with custom ones to handle input size
        self.features = nn.Sequential(
            resnet.conv1,
            resnet.bn1,
            resnet.relu,
            resnet.maxpool,
            resnet.layer1,
            resnet.layer2,
            resnet.layer3,
            resnet.layer4,
            resnet.avgpool
        )

        # Calculate last hidden size based on input size
        if input_size[1] == 32:
            self.last_hid = 512
        elif input_size[1] == 84:
            self.last_hid = 512
        elif input_size[1] == 96:
            self.last_hid = 1440

        # Classifier layer based on the number of classes
        self.classifier = nn.Linear(self.last_hid, num_classes)

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

def resnet18(num_classes=1, nf=64, input_size=(3, 32, 32), pretrained=True):
    return ResNet(num_classes=num_classes, nf=nf, input_size=input_size, pretrained=pretrained)
