"""Network architectures for point cloud regression."""
import torch
import torch.nn as nn

class PointNet(nn.Module):
    """Standard PointNet architecture for point cloud regression."""
    def __init__(self, num_points=1024, input_dim=6, output_dim=6, with_dino=False):
        super().__init__()
        self.num_points = num_points
        self.with_dino = with_dino
        
        # If using DINO, we project xyz+rgb (6D) to 32D and concat with DINO (32D) = 64D
        if with_dino:
            self.proj_xyz_rgb = nn.Linear(6, 32)  # Project xyz+rgb to 32D
            self.proj_bn = nn.BatchNorm1d(32)
            pointnet_input_dim = 64  # 32D (projected xyz+rgb) + 32D (DINO)
        else:
            pointnet_input_dim = input_dim  # 3 (xyz) or 6 (xyz+rgb)
        
        # MLP layers for feature extraction
        self.conv1 = nn.Conv1d(pointnet_input_dim, 64, 1)
        self.conv2 = nn.Conv1d(64, 128, 1)
        self.conv3 = nn.Conv1d(128, 256, 1)
        self.conv4 = nn.Conv1d(256, 1024, 1)
        self.bn1 = nn.BatchNorm1d(64)
        self.bn2 = nn.BatchNorm1d(128)
        self.bn3 = nn.BatchNorm1d(256)
        self.bn4 = nn.BatchNorm1d(1024)
        
        # Regression head
        self.fc1 = nn.Linear(1024, 512)
        self.fc2 = nn.Linear(512, 256)
        self.fc3 = nn.Linear(256, output_dim)
        self.bn5 = nn.BatchNorm1d(512)
        self.bn6 = nn.BatchNorm1d(256)
        
        self.relu = nn.ReLU()
        self.dropout = nn.Dropout(0.3)
    
    def forward(self, x, dino_features=None):
        """
        Forward pass.
        
        Args:
            x: (B, N, input_dim) point features - either (B, N, 3) for xyz or (B, N, 6) for xyz+rgb
            dino_features: (B, N, 32) DINO features if with_dino=True, else None
        """
        if self.with_dino:
            # Project xyz+rgb (6D) to 32D
            # x: (B, N, 6)
            x_proj = self.relu(self.proj_bn(self.proj_xyz_rgb(x).transpose(1, 2))).transpose(1, 2)  # (B, N, 32)
            
            # Concatenate with DINO features
            # x_proj: (B, N, 32), dino_features: (B, N, 32)
            x = torch.cat([x_proj, dino_features], dim=2)  # (B, N, 64)
        
        # x: (B, N, pointnet_input_dim) -> (B, pointnet_input_dim, N)
        x = x.transpose(2, 1)
        
        # Feature extraction layers
        x = self.relu(self.bn1(self.conv1(x)))  # (B, 64, N)
        x = self.relu(self.bn2(self.conv2(x)))  # (B, 128, N)
        x = self.relu(self.bn3(self.conv3(x)))  # (B, 256, N)
        x = self.bn4(self.conv4(x))  # (B, 1024, N)
        
        # Global max pooling
        x = torch.max(x, 2, keepdim=True)[0]  # (B, 1024, 1)
        x = x.view(-1, 1024)  # (B, 1024)
        
        # Regression head
        x = self.relu(self.bn5(self.fc1(x)))
        x = self.dropout(x)
        x = self.relu(self.bn6(self.fc2(x)))
        x = self.dropout(x)
        x = self.fc3(x)
        
        return x

