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

# 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 SimCLRDataset(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: Optional 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(in_channels = 3, out_channels = 32, kernel_size = 3, stride=2, padding=1),   # 178 -> 89
      nn.ReLU(),
      nn.Conv2d(in_channels = 32, out_channels = 64, kernel_size = 3, stride=2, padding=1),  # 89 -> 45
      nn.ReLU(),
      nn.Conv2d(in_channels = 64, out_channels = 128, kernel_size = 3, stride=2, padding=1), # 45 -> 23
      nn.ReLU(),
      nn.Conv2d(in_channels = 128, out_channels = 256, kernel_size = 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 SimCLR(nn.Module):
  """
  Simple convolutional autoencoder for image embeddings.
  The parameter is:
  - encoder: Encoder to use.
  - embedding_dim: Dimension of the embedding space.
  - projection_dim: Dimension of the projection space.
  """
  def __init__(self, encoder, embedding_dim = 128, projection_dim = 64):
    super().__init__()
    self.encoder = encoder
    self.projector = nn.Sequential(
      nn.Linear(embedding_dim, 256),
      nn.ReLU(),
      nn.Linear(256, projection_dim)
    )

  def forward(self, x):
    h = self.encoder(x)
    z = self.projector(h)
    return F.normalize(z, dim = 1)

def nt_xent_loss(z_i, z_j, temperature = 0.5):
  batch_size = z_i.size(0)
  z = torch.cat([z_i, z_j], dim = 0)  # [2 * batch, dim]
  z = F.normalize(z, dim = 1)         # Ensure unit norm

  # Cosine similarity matrix
  sim = torch.matmul(z, z.T) / temperature  # [2 * batch, 2 * batch]

  # Mask to remove similarity with itself
  mask = torch.eye(2 * batch_size, dtype = torch.bool).to(z.device)
  sim = sim.masked_fill(mask, float('-inf'))

  # Positive pairs: i-th in first half with i-th in second half
  pos = torch.cat([torch.arange(batch_size, 2 * batch_size), torch.arange(0, batch_size)]).to(z.device)
  loss = F.cross_entropy(sim, pos)
  return loss