import torch
import torch.nn as nn
import torch.nn.functional as F

def gaussian_mi_unsupervised(X, Z, eps=1e-4):
    """
    Computes Mutual Information strictly between two continuous feature spaces.
    L2 normalization strictly prevents the network from cheating by scaling magnitudes.
    No discrete labels (Y) are used here.
    """
    N = X.shape[0]
    dx = X.shape[1]
    dz = Z.shape[1]
    
    # 1. L2 Normalize to mathematically prevent the "scaling cheat"
    X = F.normalize(X, p=2, dim=1)
    Z = F.normalize(Z, p=2, dim=1)
    
    # 2. Center to zero-mean
    X = X - X.mean(0, keepdim=True)
    Z = Z - Z.mean(0, keepdim=True)
    
    XZ = torch.cat([X, Z], dim=1) 
    
    # 3. Sample covariances with regularization
    reg_xy = eps * torch.eye(dx + dz, device=X.device)
    reg_x  = eps * torch.eye(dx, device=X.device)
    reg_z  = eps * torch.eye(dz, device=X.device)
    
    Sigma_XZ = (XZ.T @ XZ) / (N - 1) + reg_xy
    Sigma_X  = (X.T  @ X)  / (N - 1) + reg_x
    Sigma_Z  = (Z.T  @ Z)  / (N - 1) + reg_z
    
    _, ld_xz = torch.linalg.slogdet(Sigma_XZ)
    _, ld_x  = torch.linalg.slogdet(Sigma_X)
    _, ld_z  = torch.linalg.slogdet(Sigma_Z)
    
    mi = 0.5 * (ld_x + ld_z - ld_xz)
    return mi.clamp(min=0.0)


def compute_stable_pid(vs, vu, as_, au, fs, fu):
    """
    Calculates PID solely based on cross-modal interactions.
    Dynamically handles missing modalities (e.g. if only video and flow are used).
    """
    # Initialize loss tensors on the correct device
    device = vs.device if vs is not None else (as_.device if as_ is not None else fs.device)
    loss_shared = torch.tensor(0.0, device=device)
    loss_unique = torch.tensor(0.0, device=device)

    # --- SHARED LOSS ---
    # Maximize redundancy between shared spaces (minimize negative MI)
    # We want these spaces to overlap as much as possible.
    if vs is not None and as_ is not None:
        loss_shared -= gaussian_mi_unsupervised(vs, as_)
    if vs is not None and fs is not None:
        loss_shared -= gaussian_mi_unsupervised(vs, fs)
    if as_ is not None and fs is not None:
        loss_shared -= gaussian_mi_unsupervised(as_, fs)

    # --- UNIQUE LOSS ---
    # Minimize redundancy between unique spaces (minimize positive MI)
    # We force these spaces to be entirely independent/orthogonal.
    if vu is not None and au is not None:
        loss_unique += gaussian_mi_unsupervised(vu, au)
    if vu is not None and fu is not None:
        loss_unique += gaussian_mi_unsupervised(vu, fu)
    if au is not None and fu is not None:
        loss_unique += gaussian_mi_unsupervised(au, fu)

    return loss_shared, loss_unique


class PIDProjectionHeads(nn.Module):
    """
    Projects the high-dimensional split embeddings into a lower-dimensional
    space to ensure the covariance matrix remains full-rank given the batch size.
    """
    def __init__(self, dim_map, proj_dim=6):
        super().__init__()
        self.proj_dim = proj_dim
        self.heads = nn.ModuleDict()
        for k, in_dim in dim_map.items():
            # k is e.g. 'vs', 'vu', 'as', 'au', 'fs', 'fu'
            self.heads[k] = nn.Sequential(
                nn.Linear(in_dim, proj_dim),
                nn.BatchNorm1d(proj_dim),
                nn.ReLU(inplace=True),
                nn.Linear(proj_dim, proj_dim)
            )

    def forward(self, vs=None, vu=None, as_=None, au=None, fs=None, fu=None):
        out = {}
        if vs is not None: out['vs'] = self.heads['vs'](vs)
        if vu is not None: out['vu'] = self.heads['vu'](vu)
        if as_ is not None: out['as'] = self.heads['as'](as_)
        if au is not None: out['au'] = self.heads['au'](au)
        if fs is not None: out['fs'] = self.heads['fs'](fs)
        if fu is not None: out['fu'] = self.heads['fu'](fu)
        return out


class PIDSplittingLoss(nn.Module):
    def __init__(self, pid_proj, alpha_shared=1.0, alpha_unique=1.0,
                 use_video=True, use_audio=True, use_flow=True, gamma=None):
        super().__init__()
        self.pid_proj = pid_proj
        self.alpha_shared = alpha_shared
        self.alpha_unique = alpha_unique
        # gamma is no longer strictly used in the unsupervised formulation, 
        # but kept in the signature to avoid breaking your train script arguments.
        self.use_video = use_video
        self.use_audio = use_audio
        self.use_flow  = use_flow

    def forward(self, v_shared=None, v_unique=None, 
                a_shared=None, a_unique=None, 
                f_shared=None, f_unique=None):
        
        # 1. Project all active features to low-dim space
        proj_feats = self.pid_proj(
            vs=v_shared, vu=v_unique,
            as_=a_shared, au=a_unique,
            fs=f_shared, fu=f_unique
        )

        vs_p = proj_feats.get('vs')
        vu_p = proj_feats.get('vu')
        as_p = proj_feats.get('as')
        au_p = proj_feats.get('au')
        fs_p = proj_feats.get('fs')
        fu_p = proj_feats.get('fu')

        # 2. Compute Unsupervised PID Losses
        loss_shared, loss_unique = compute_stable_pid(
            vs_p, vu_p, as_p, au_p, fs_p, fu_p
        )

        # 3. Aggregate Loss
        total_loss = (self.alpha_shared * loss_shared) + (self.alpha_unique * loss_unique)

        # 4. Logging
        log_dict = {
            'pid_loss_shared': loss_shared.item(),
            'pid_loss_unique': loss_unique.item(),
            'pid_total_loss': total_loss.item()
        }

        return total_loss, log_dict