import torch
from torchvision import transforms
import torch.nn as nn
from torch.utils.data import Dataset
import torch.nn.functional as F
from PIL import Image
import os
import copy

# Resize image to 178 x 178, standardizes each color channel (RGB) of your image and convert it to a Tensor
preprocess = transforms.Compose([
  # All images of my celebrity dataset are 178x218
  transforms.Resize(size = (178, 178)),
  transforms.ToTensor(),
  transforms.Normalize(mean = [0.485, 0.456, 0.406], std = [0.229, 0.224, 0.225]),
])

# Resize image to 178 x 178
# crop a random portion of image and resize it to a given size
# horizontally flip the given image randomly with a given probability
# randomly change the brightness, contrast, saturation and hue of an image,
# Randomly convert image to grayscale with a probability of p
# Blurs image with randomly chosen Gaussian blur.
# standardizes each color channel (RGB) of your image and convert it to a Tensor
preprocess_train = transforms.Compose([
  # All images of my celebrity dataset are 178x218
  transforms.Resize(size = (178, 178)),  # Resize directly to 178x178
    transforms.RandomResizedCrop(size = 178, scale=(0.2, 1.0)),  # Optional: for SimCLR, keep this for strong augmentation
    transforms.RandomHorizontalFlip(),
    transforms.RandomApply(transforms = [transforms.ColorJitter(brightness = 0.4, contrast = 0.4, saturation = 0.4, hue = 0.1)], p = 0.8),
    transforms.RandomGrayscale(p = 0.2),
    transforms.GaussianBlur(kernel_size = 3),
    transforms.ToTensor(),
    transforms.Normalize(mean = [0.485, 0.456, 0.406], std = [0.229, 0.224, 0.225])
])

class BYOLDataset(Dataset):
  """
  Class to read images from a folder without labels and apply to them a transformation (resize, normalize, ...).
  The parameters are:
  - image_folder: Directory with images.
  - transform: Transform to be applied on a sample.
  """
  def __init__(self, image_folder,  transform_train = None, transform_infer = None, mode = 'train'):
    self.image_folder = image_folder
    self.transform_train = transform_train
    self.transform_infer = transform_infer
    self.mode = mode
    # self.images = [f for f in os.listdir(image_folder) if f.lower().endswith(('.jpg', '.jpeg', '.png'))][:1000]
    self.images = [f for f in os.listdir(image_folder) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]

  def __len__(self):
    return len(self.images)

  def __getitem__(self, idx):
    image_file = os.path.join(self.image_folder, self.images[idx])
    image = Image.open(image_file).convert('RGB')
    if self.mode == 'train':
      xi = self.transform_train(image)
      xj = self.transform_train(image)
      return xi, xj
    elif self.mode == 'inference':
      image = self.transform_infer(image)
      return image, self.images[idx]

class SimpleCNNEncoder(nn.Module):
  def __init__(self, embedding_dim = 128):
    super().__init__()
    self.conv = nn.Sequential(
      nn.Conv2d(3, 32, 3, stride=2, padding=1),   # 178 -> 89
      nn.ReLU(),
      nn.Conv2d(32, 64, 3, stride=2, padding=1),  # 89 -> 45
      nn.ReLU(),
      nn.Conv2d(64, 128, 3, stride=2, padding=1), # 45 -> 23
      nn.ReLU(),
      nn.Conv2d(128, 256, 3, stride=2, padding=1),# 23 -> 12
      nn.ReLU(),
      nn.AdaptiveAvgPool2d((1, 1)),               # [B, 256, 1, 1]
      nn.Flatten(),                               # [B, 256]
    )
    self.fc = nn.Linear(256, embedding_dim)

  def forward(self, x):
    embedding = self.conv(x)
    embedding = self.fc(embedding)
    return embedding

class MLP(nn.Module):
  def __init__(self, in_dim, hidden_dim, out_dim):
    super().__init__()
    self.net = nn.Sequential(
      nn.Linear(in_dim, hidden_dim),
      nn.BatchNorm1d(hidden_dim),
      nn.ReLU(),
      nn.Linear(hidden_dim, out_dim)
    )
  def forward(self, x):
    return self.net(x)
    
class BYOL(nn.Module):
  """
  Simple convolutional autoencoder for image embeddings.
  The parameter is:
  - base_encoder: Encoder to use.
  - embedding_dim: Dimension of the embedding space.
  - projection_dim: Dimension of the projection space.
  - hidden_dim: Dimension of the hidden layer in the MLP.
  - ema_decay: Exponential moving average decay for target network update.
  """
  def __init__(self, base_encoder, embedding_dim = 128, projection_dim = 64, hidden_dim = 256, ema_decay = 0.99):
    super().__init__()
    # Online network
    self.online_encoder = base_encoder
    self.online_projector = MLP(embedding_dim, hidden_dim, projection_dim)
    self.online_predictor = MLP(projection_dim, hidden_dim, projection_dim)
    # Target network (EMA)
    self.target_encoder = copy.deepcopy(base_encoder)
    self.target_projector = copy.deepcopy(self.online_projector)
    for param in self.target_encoder.parameters():
      param.requires_grad = False
    for param in self.target_projector.parameters():
      param.requires_grad = False
    self.ema_decay = ema_decay

  @torch.no_grad()
  def _update_target(self):
    for online, target in zip(self.online_encoder.parameters(), self.target_encoder.parameters()):
      target.data = self.ema_decay * target.data + (1 - self.ema_decay) * online.data
    for online, target in zip(self.online_projector.parameters(), self.target_projector.parameters()):
      target.data = self.ema_decay * target.data + (1 - self.ema_decay) * online.data

  def forward(self, x1, x2):
    # Online
    o1 = self.online_predictor(self.online_projector(self.online_encoder(x1)))
    o2 = self.online_predictor(self.online_projector(self.online_encoder(x2)))
    # Target
    with torch.no_grad():
      t1 = self.target_projector(self.target_encoder(x1))
      t2 = self.target_projector(self.target_encoder(x2))
    return o1, t2.detach(), o2, t1.detach()

def byol_loss_func(p, z):
  # Negative cosine similarity
  p = F.normalize(p, dim=1)
  z = F.normalize(z, dim=1)
  return 2 - 2 * (p * z).sum(dim=1).mean()