import numpy as np
import torch

from suite11_latent_moe import (
    OpportunityRouter,
    authority_adjusted_weights,
    latent_specialist_loss,
)


def test_authority_adjusted_weights_preserve_probability_simplex():
    p = np.array([[0.50, 0.20, 0.20, 0.10], [0.10, 0.30, 0.30, 0.30]])
    w = authority_adjusted_weights(p, alpha=0.5)
    assert w.shape == p.shape
    assert np.allclose(w.sum(axis=1), 1.0)
    assert np.all(w >= 0)
    # Specialist mass is shrunk by alpha and the remainder returns to NULL.
    assert np.allclose(w[:, 1:].sum(axis=1), 0.5 * p[:, 1:].sum(axis=1))


def test_router_outputs_null_plus_domains():
    m = OpportunityRouter(input_dim=6, n_domains=3, hidden=12, dropout=0.0)
    x = torch.randn(8, 6)
    logits = m(x)
    assert logits.shape == (8, 4)
    assert torch.isfinite(logits).all()


def test_latent_specialist_loss_uses_only_nonnull_responsibility():
    output = {
        "counterfactual_logit": torch.tensor([[0.0, 1.0], [1.0, -1.0]], requires_grad=True),
        "residuals": torch.tensor([[0.2, 0.1], [0.1, -0.2]], requires_grad=True),
    }
    y = torch.tensor([1.0, 0.0])
    responsibilities = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
    loss = latent_specialist_loss(output, y, responsibilities, magnitude_lambda=0.01)
    assert torch.isfinite(loss["total"])
    assert loss["domain_mass"].shape == (2,)
    assert float(loss["domain_mass"][0]) == 1.0
    assert float(loss["domain_mass"][1]) == 0.0
