"""Information-preserving semantic views; matched additive/product fusion."""
from __future__ import annotations
import torch
from torch import nn
from s34_views import VIEWS


class ResidualBlock(nn.Module):
    def __init__(self, width, dropout):
        super().__init__()
        self.layers = nn.Sequential(nn.LayerNorm(width), nn.Linear(width, width),
                                    nn.GELU(), nn.Linear(width, width), nn.Dropout(dropout))

    def forward(self, x):
        return x + self.layers(x)


def parameter_count(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)


def matched_width(input_dim, views, config):
    target = parameter_count(IPMVCL(input_dim, views, "A2", config))
    blocks = int(config.get("residual_blocks", 2))
    # A0: input projection/norm, fixed number of residual blocks, one linear head.
    def count(w):
        return 2*blocks*w*w + (input_dim+4*blocks+4)*w + 1
    width = min(range(4, 2049), key=lambda w: abs(count(w)-target))
    if abs(count(width)/target-1) > .05:
        raise ValueError("Cannot parameter-match A0M within 5%")
    return width


class IPMVCL(nn.Module):
    def __init__(self, input_dim, views, arm, config):
        super().__init__()
        if arm not in ("A0", "A0M", "A1", "A2", "P1", "A3"):
            raise ValueError(f"Unknown model arm {arm}")
        self.arm, self.input_dim = arm, int(input_dim)
        self.config = dict(config)
        self.views = {v: list(views[v]) for v in VIEWS}
        width = int(config.get("backbone_width", 128))
        if arm == "A0M":
            width = int(config.get("matched_width") or matched_width(input_dim, views, config))
        e, r = int(config.get("view_dim", 32)), int(config.get("interaction_rank", 24))
        dropout, blocks = float(config.get("dropout", .1)), int(config.get("residual_blocks", 2))
        self.full = nn.Sequential(nn.Linear(input_dim, width), nn.LayerNorm(width), nn.GELU(),
                                  *[ResidualBlock(width, dropout) for _ in range(blocks)])
        if arm in ("A0", "A0M"):
            self.head = nn.Linear(width, 1)
            return
        if any(not self.views[v] for v in VIEWS):
            raise ValueError("Specialized views cannot be empty")
        self.encoders = nn.ModuleDict({
            v: nn.Sequential(nn.Linear(len(self.views[v]), e), nn.LayerNorm(e), nn.GELU(),
                             nn.Dropout(dropout), nn.Linear(e, e), nn.LayerNorm(e), nn.GELU())
            for v in VIEWS})
        self.projections = nn.ModuleDict({k: nn.Linear(e, r, bias=False)
            for k in ("student", "course_student", "history", "course_history")})
        fusion_dim = width+3*e+2*r
        self.head = nn.Sequential(nn.LayerNorm(fusion_dim), nn.Linear(fusion_dim, width),
                                  nn.GELU(), nn.Dropout(dropout),
                                  ResidualBlock(width, dropout), nn.Linear(width, 1))
        if arm == "A3":
            self.aux_heads = nn.ModuleDict({v: nn.Linear(e, 1) for v in VIEWS})

    def forward(self, x, zero_interactions=(), zero_views=(), return_details=False):
        if set(zero_interactions)-{"sc", "hc"}:
            raise ValueError("Unknown interaction intervention")
        full = self.full(x)
        if self.arm in ("A0", "A0M"):
            logit = self.head(full).squeeze(-1)
            return (logit, {"full": full, "aux": {}}) if return_details else logit
        z = {v: self.encoders[v](x[:, self.views[v]]) for v in VIEWS}
        for v in zero_views:
            if v not in VIEWS:
                raise ValueError(f"Unknown view intervention {v}")
            z[v] = torch.zeros_like(z[v])
        s = self.projections["student"](z["student"])
        cs = self.projections["course_student"](z["course"])
        h = self.projections["history"](z["history"])
        ch = self.projections["course_history"](z["course"])
        sc, hc = ((s+cs)/2, (h+ch)/2) if self.arm == "A1" else (s*cs, h*ch)
        if "sc" in zero_interactions:
            sc = torch.zeros_like(sc)
        if "hc" in zero_interactions:
            hc = torch.zeros_like(hc)
        u = torch.cat([full]+[z[v] for v in VIEWS]+[sc, hc], dim=1)
        logit = self.head(u).squeeze(-1)
        if not return_details:
            return logit
        aux = {v: self.aux_heads[v](z[v]).squeeze(-1) for v in VIEWS} if self.arm == "A3" else {}
        return logit, dict(full=full, sc=sc, hc=hc, aux=aux, **z)
