"""
Differentiable Spherical Dictionary Routing (DSDR)
===================================================
Production-grade PyTorch implementation with exact analytical Jacobian derivation,
dual entropy regularization, defensive precision casting, and verification tests.
"""

import math
from contextlib import nullcontext
from typing import Dict, Optional, Tuple, Union

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


# =============================================================================
# 0. AUTOCAST COMPATIBILITY HELPER
# =============================================================================

def _disable_autocast(device: torch.device):
    """
    Returns a device-agnostic, warning-free context manager to disable autocast.
    Supports CUDA, CPU, MPS, and XPU natively in PyTorch 2.x, with PyTorch 1.x fallback.
    """
    dev_type = device.type
    if hasattr(torch, "amp") and hasattr(torch.amp, "autocast"):
        if dev_type in ["cuda", "cpu", "mps", "xpu"]:
            return torch.amp.autocast(device_type=dev_type, enabled=False)
        return nullcontext()
    elif dev_type == "cuda" and torch.cuda.is_available():
        return torch.cuda.amp.autocast(enabled=False)
    return nullcontext()


# =============================================================================
# 1. CORE ROUTING MODULE
# =============================================================================

class SphericalDictionaryRouting(nn.Module):
    """
    Differentiable Spherical Dictionary Routing (DSDR) Layer.

    Decomposes continuous latents z into radial magnitude r_eps and directional vector u,
    routing u over a unit-hypersphere codebook via a Nadaraya-Watson kernel operator.

    Mathematical Formulation:
        r_eps = sqrt(||z||_2^2 + eps)
        u = z / r_eps
        p_k = softmax(<u, c_k> / T)
        u_bar = sum_k p_k * c_k
        z_rep = r_eps * u_bar

    Theoretical Properties & Bounds:
        - Canonical Temperature Initialization: T*(d) = d^(-1/2) normalizes isotropic background
          logit variance to 1.0 under Haar measure assumptions at initialization.
          During training, representation correlations alter empirical variance.
        - Operator Norm Upper Bound: ||J(z)||_2 <= 1 + 1/T = 1 + sqrt(d) holds as an analytical
          upper bound derived via norm subadditivity under normalized centroids.
        - Radial Direction Bound:
            * Idealized (eps = 0): Strictly non-expansive along radial variations (||J z_hat|| <= 1.0).
            * Regularized (eps > 0): ||J z_hat||_2 <= (||z|| / r_eps) * (1 + eps / (T * r_eps^2)),
              converging to <= 1.0 in the operational regime ||z||^2 >> eps.
    """

    def __init__(
        self,
        d_model: int,
        num_centroids: int,
        temperature: Optional[float] = None,
        batch_entropy_weight: float = 0.0,
        sample_entropy_weight: float = 0.0,
        eps: float = 1e-12,
    ):
        super().__init__()
        # Structural validation
        if not isinstance(d_model, int) or d_model <= 0:
            raise ValueError(f"d_model must be a positive integer, got {d_model}")
        if not isinstance(num_centroids, int) or num_centroids <= 0:
            raise ValueError(f"num_centroids must be a positive integer, got {num_centroids}")

        # Numerical parameter validation
        if not math.isfinite(eps) or eps <= 0.0:
            raise ValueError(f"eps must be finite and positive, got {eps}")
        if not math.isfinite(batch_entropy_weight) or batch_entropy_weight < 0.0:
            raise ValueError(f"batch_entropy_weight must be finite and non-negative, got {batch_entropy_weight}")
        if not math.isfinite(sample_entropy_weight) or sample_entropy_weight < 0.0:
            raise ValueError(f"sample_entropy_weight must be finite and non-negative, got {sample_entropy_weight}")

        self.d_model = d_model
        self.num_centroids = num_centroids
        self.batch_entropy_weight = batch_entropy_weight
        self.sample_entropy_weight = sample_entropy_weight
        self.eps = eps

        # Initialize dictionary centroids randomly on S^(d-1)
        raw_centroids = torch.randn(num_centroids, d_model)
        self.centroids = nn.Parameter(F.normalize(raw_centroids, p=2, dim=-1, eps=eps))

        # Temperature initialization
        if temperature is not None:
            if not math.isfinite(temperature) or temperature <= 0.0:
                raise ValueError(f"temperature must be finite and positive, got {temperature}")
            t_val = float(temperature)
        else:
            t_val = 1.0 / math.sqrt(d_model)

        self.register_buffer(
            "temperature",
            torch.tensor(t_val, dtype=torch.float32),
            persistent=True,
        )

        # Cached statistics
        self.last_batch_entropy: Optional[torch.Tensor] = None
        self.last_sample_entropy: Optional[torch.Tensor] = None
        self.last_perplexity: Optional[torch.Tensor] = None

    def forward(
        self,
        z: torch.Tensor,
        hard: bool = False,
        return_indices: bool = False,
        return_entropy_loss: bool = False,
    ) -> Union[
        torch.Tensor,
        Tuple[torch.Tensor, torch.Tensor],
        Tuple[torch.Tensor, torch.Tensor, torch.Tensor],
    ]:
        """
        Forward pass with adaptive precision routing and Straight-Through Estimator.

        Args:
            z: Continuous latents of shape [..., d_model]
            hard: If True, executes discrete centroid projection:
                  - Training: Straight-Through Estimator (discrete forward, soft backward).
                  - Evaluation: Pure discrete token selection.
            return_indices: If True, returns discrete token IDs of shape [...].
            return_entropy_loss: If True, returns combined scalar entropy loss.

        Returns:
            z_rep: Routed representation matching the shape and dtype of z.
            indices (optional): Discrete centroid indices of shape [...].
            entropy_loss (optional): Combined entropy regularization scalar.
        """
        if not torch.is_floating_point(z):
            raise TypeError(f"Input z must be a floating-point tensor, got {z.dtype}")
        if z.numel() == 0:
            raise ValueError(f"Input tensor z is empty (shape: {z.shape}).")

        orig_shape = z.shape
        orig_dtype = z.dtype
        d = orig_shape[-1]
        if d != self.d_model:
            raise ValueError(f"Expected last dimension {self.d_model}, got {d}")

        # Precision policy: use float64 if z is float64, otherwise float32
        compute_dtype = torch.float64 if orig_dtype == torch.float64 else torch.float32

        # Flatten leading dimensions to 2D [N, d]
        z_flat = z.reshape(-1, d).to(compute_dtype)

        # 1. Radial-directional decomposition
        radius = torch.sqrt(torch.sum(z_flat ** 2, dim=-1, keepdim=True) + self.eps)
        u = z_flat / radius

        # 2. Routing calculations (disabling autocast warning-free across devices)
        with _disable_autocast(z.device):
            c_norm = F.normalize(self.centroids.to(compute_dtype), p=2, dim=-1, eps=self.eps)
            temp = self.temperature.to(compute_dtype)
            logits = F.linear(u, c_norm) / temp

            probs = F.softmax(logits, dim=-1)
            u_bar_soft = torch.matmul(probs, c_norm)
            k_star = torch.argmax(logits, dim=-1)

            # 3. Discretization Path with Straight-Through Estimator (STE)
            if hard:
                u_hard = c_norm[k_star]
                if self.training:
                    u_bar = u_bar_soft + (u_hard - u_bar_soft).detach()
                else:
                    u_bar = u_hard
            else:
                u_bar = u_bar_soft

            z_rep_computed = radius * u_bar

            # 4. Dual Entropy Regularization
            entropy_loss = None
            if self.training and (self.batch_entropy_weight > 0.0 or self.sample_entropy_weight > 0.0):
                entropy_loss = torch.tensor(0.0, device=z.device, dtype=compute_dtype)

                # Batch-averaged entropy (maximization encourages codebook utilization)
                if self.batch_entropy_weight > 0.0:
                    p_batch = probs.mean(dim=0)
                    h_batch = -(p_batch * p_batch.clamp_min(1e-12).log()).sum()
                    entropy_loss = entropy_loss - self.batch_entropy_weight * h_batch
                    self.last_batch_entropy = h_batch.detach()
                    self.last_perplexity = torch.exp(h_batch).detach()
                else:
                    self.last_batch_entropy = None
                    self.last_perplexity = None

                # Sample-level entropy (minimization encourages sharp routing)
                if self.sample_entropy_weight > 0.0:
                    h_sample = -(probs * probs.clamp_min(1e-12).log()).sum(dim=-1).mean()
                    entropy_loss = entropy_loss + self.sample_entropy_weight * h_sample
                    self.last_sample_entropy = h_sample.detach()
                else:
                    self.last_sample_entropy = None

        # Reshape and restore original tensor dtype
        z_rep = z_rep_computed.view(orig_shape).to(orig_dtype)
        k_star = k_star.view(orig_shape[:-1])

        if return_indices and return_entropy_loss:
            return z_rep, k_star, entropy_loss
        elif return_indices:
            return z_rep, k_star
        elif return_entropy_loss:
            return z_rep, entropy_loss
        return z_rep


# =============================================================================
# 2. EXACT ANALYTICAL JACOBIAN & FINITE DIFFERENCE VALIDATION
# =============================================================================

def compute_analytical_jacobian(
    z: torch.Tensor,
    centroids: torch.Tensor,
    temperature: Union[float, torch.Tensor],
    eps: float = 1e-12,
) -> torch.Tensor:
    """
    Computes the exact theoretical Jacobian J = d(z_rep)/d(z) for a single vector z.

    Formula derived directly from implemented forward mapping:
        J = u_bar * u^T + (1 / T) * Cov_p(C) * (I - u * u^T)
    where r_eps = sqrt(||z||^2 + eps) and u = z / r_eps.
    """
    dtype = z.dtype
    device = z.device
    z_f = z.to(dtype=dtype, device=device)
    c_norm = F.normalize(centroids.to(dtype=dtype, device=device), p=2, dim=-1, eps=eps)
    t_val = float(temperature.item()) if isinstance(temperature, torch.Tensor) else float(temperature)

    r_eps = torch.sqrt(torch.sum(z_f ** 2) + eps)
    u = z_f / r_eps

    logits = torch.matmul(c_norm, u) / t_val
    p = F.softmax(logits, dim=-1)
    u_bar = torch.matmul(p, c_norm)

    Cov = torch.matmul(c_norm.T, p.unsqueeze(-1) * c_norm) - torch.outer(u_bar, u_bar)

    d = z_f.numel()
    projector = torch.eye(d, dtype=dtype, device=device) - torch.outer(u, u)

    J = torch.outer(u_bar, u) + (1.0 / t_val) * torch.matmul(Cov, projector)
    return J


def compute_central_finite_difference_jacobian(
    forward_fn,
    z: torch.Tensor,
    h: float = 1e-5,
) -> torch.Tensor:
    """
    Computes numerical Jacobian via central finite differences in double precision.
    """
    d = z.numel()
    J = torch.zeros(d, d, dtype=z.dtype, device=z.device)

    for i in range(d):
        z_plus = z.clone()
        z_minus = z.clone()
        z_plus[i] += h
        z_minus[i] -= h

        f_plus = forward_fn(z_plus)
        f_minus = forward_fn(z_minus)

        J[:, i] = (f_plus - f_minus) / (2.0 * h)

    return J


# =============================================================================
# 3. QUANTIZATION & CODEBOOK HEALTH DIAGNOSTICS
# =============================================================================

@torch.no_grad()
def evaluate_quantization_diagnostics(
    layer: SphericalDictionaryRouting,
    eval_dataloader,
    encoder: nn.Module,
    decoder: nn.Module,
) -> Dict[str, float]:
    """
    Evaluates the discrete inference gap (Delta_MSE), perplexity, and active code utilization.
    Includes input shape validation and empty-loader guards.
    """
    layer.eval()
    encoder.eval()
    decoder.eval()
    device = next(layer.parameters()).device

    total_soft_mse = 0.0
    total_hard_mse = 0.0
    num_samples = 0
    centroid_counts = torch.zeros(layer.num_centroids, dtype=torch.long, device=device)

    for batch in eval_dataloader:
        x = batch[0].to(device) if isinstance(batch, (tuple, list)) else batch.to(device)
        B = x.shape[0]
        if B == 0:
            continue

        z_e = encoder(x)
        if z_e.shape[-1] != layer.d_model:
            raise ValueError(f"Encoder output dimension {z_e.shape[-1]} does not match layer {layer.d_model}")

        # 1. Soft reconstruction
        z_soft = layer(z_e, hard=False)
        x_rec_soft = decoder(z_soft)
        if x_rec_soft.shape != x.shape:
            raise ValueError(f"Decoder output shape {x_rec_soft.shape} does not match input {x.shape}")
        soft_mse = torch.mean((x - x_rec_soft) ** 2).item()

        # 2. Hard reconstruction
        z_hard, k_star = layer(z_e, hard=True, return_indices=True)
        x_rec_hard = decoder(z_hard)
        hard_mse = torch.mean((x - x_rec_hard) ** 2).item()

        total_soft_mse += soft_mse * B
        total_hard_mse += hard_mse * B
        num_samples += B

        centroid_counts += torch.bincount(k_star.view(-1), minlength=layer.num_centroids)

    if num_samples == 0:
        raise RuntimeError("Evaluation dataloader produced zero valid samples.")

    avg_soft_mse = total_soft_mse / num_samples
    avg_hard_mse = total_hard_mse / num_samples
    delta_mse = avg_hard_mse - avg_soft_mse

    probs_usage = centroid_counts.float() / centroid_counts.sum()
    entropy = -torch.sum(probs_usage * probs_usage.clamp_min(1e-12).log()).item()
    perplexity = math.exp(entropy)
    active_code_fraction = (centroid_counts > 0).float().mean().item()

    diagnostics = {
        "Soft_MSE": avg_soft_mse,
        "Hard_MSE": avg_hard_mse,
        "Delta_MSE": delta_mse,
        "Active_Codes_Pct": active_code_fraction * 100.0,
        "Codebook_Perplexity": perplexity,
        "Theoretical_Max_Perplexity": float(layer.num_centroids),
    }

    print("\n" + "=" * 55)
    print("Spherical Dictionary Quantization Diagnostics")
    print("=" * 55)
    for k, v in diagnostics.items():
        print(f"  {k:28s}: {v:.4f}")
    print("=" * 55)

    return diagnostics


# =============================================================================
# 4. RIGOROUS UNIT TEST SUITE
# =============================================================================

def run_all_unit_tests():
    """
    Executes unit tests covering input validation, analytical Jacobian correctness,
    native PyTorch gradcheck on the module itself, finite differences,
    AMP output/gradient fidelity, and extreme temperature regimes.
    """
    print("\n" + "=" * 70)
    print("RUNNING ADVANCED DSDR UNIT TESTS & VERIFICATION SUITE")
    print("=" * 70)

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    d_model = 16
    num_centroids = 64
    layer = SphericalDictionaryRouting(
        d_model=d_model,
        num_centroids=num_centroids,
        batch_entropy_weight=0.01,
        sample_entropy_weight=0.005,
    ).to(device)

    # -------------------------------------------------------------------------
    # Test 1: Defensive Input Validation
    # -------------------------------------------------------------------------
    invalid_cases = [
        {"d_model": -1, "num_centroids": 64},
        {"d_model": 16, "num_centroids": 0},
        {"d_model": 16, "num_centroids": 64, "temperature": -0.5},
        {"d_model": 16, "num_centroids": 64, "temperature": float("nan")},
        {"d_model": 16, "num_centroids": 64, "eps": -1e-5},
        {"d_model": 16, "num_centroids": 64, "batch_entropy_weight": -0.1},
        {"d_model": 16, "num_centroids": 64, "sample_entropy_weight": float("inf")},
    ]
    for case in invalid_cases:
        try:
            SphericalDictionaryRouting(**case)
            assert False, f"Failed to reject invalid input: {case}"
        except ValueError:
            pass

    # Empty tensor and non-floating validation
    try:
        layer(torch.empty(0, d_model, device=device))
        assert False, "Failed to catch empty input tensor"
    except ValueError:
        pass

    try:
        layer(torch.randint(0, 10, (4, d_model), device=device))
        assert False, "Failed to catch non-floating tensor"
    except TypeError:
        pass

    print("[PASS] Test 1: Defensive Input Validation (Types, Shapes, Finite Ranges)")

    # -------------------------------------------------------------------------
    # Test 2: Direct Module Jacobian Verification (Module vs Analytical vs FD)
    # -------------------------------------------------------------------------
    # Test the actual module instance in float64
    layer_64 = SphericalDictionaryRouting(d_model=d_model, num_centroids=num_centroids).to(torch.float64).to(device)
    temp_64 = layer_64.temperature.item()
    test_scales = [1e-4, 1.0, 10.0]

    for scale in test_scales:
        z_d = torch.randn(d_model, device=device, dtype=torch.float64, requires_grad=True)
        z_d = ((z_d / z_d.norm()) * scale).detach().clone().requires_grad_(True)

        # Forward directly through the module instance
        def forward_module(x):
            return layer_64(x.unsqueeze(0), hard=False).squeeze(0)

        J_autograd = torch.autograd.functional.jacobian(forward_module, z_d)
        J_analytical = compute_analytical_jacobian(z_d, layer_64.centroids, temp_64, layer_64.eps)

        h_step = max(1e-7, scale * 1e-5)
        J_fd = compute_central_finite_difference_jacobian(forward_module, z_d, h=h_step)

        err_autograd = torch.norm(J_analytical - J_autograd) / torch.norm(J_analytical)
        assert err_autograd < 1e-7, f"Autograd Jacobian mismatch at scale {scale}: {err_autograd.item()}"

        err_fd = torch.norm(J_analytical - J_fd) / torch.norm(J_analytical)
        assert err_fd < 1e-5, f"Finite Difference mismatch at scale {scale}: {err_fd.item()}"

    print("[PASS] Test 2: Direct Module Forward Verified Against Autograd & Finite Differences")

    # -------------------------------------------------------------------------
    # Test 3: Native PyTorch Gradcheck on the Module
    # -------------------------------------------------------------------------
    z_gc = torch.randn(2, d_model, device=device, dtype=torch.float64, requires_grad=True)
    assert torch.autograd.gradcheck(
        lambda x: layer_64(x, hard=False),
        (z_gc,),
        eps=1e-6,
        atol=1e-5,
        rtol=1e-3,
    ), "Native PyTorch gradcheck failed on module"
    print("[PASS] Test 3: Native PyTorch torch.autograd.gradcheck Passed on Module Instance")

    # -------------------------------------------------------------------------
    # Test 4: Empirical Operator Norm Bound Regression Check
    # -------------------------------------------------------------------------
    max_bound = 1.0 + 1.0 / layer.temperature.item()
    for _ in range(25):
        z_rand = torch.randn(d_model, device=device) * torch.empty(1, device=device).uniform_(0.01, 20.0)
        J_val = compute_analytical_jacobian(z_rand, layer.centroids, layer.temperature, layer.eps)
        spectral_norm = torch.linalg.svdvals(J_val)[0].item()
        assert spectral_norm <= max_bound + 1e-4, f"Bound exceeded: {spectral_norm} > {max_bound}"

    print(f"[PASS] Test 4: Empirical SVD Regression Check (All sigma_max <= 1 + sqrt(d) = {max_bound:.4f})")

    # -------------------------------------------------------------------------
    # Test 5: Extreme Temperature Regimes (T -> 0 and T -> infinity)
    # -------------------------------------------------------------------------
    layer_cold = SphericalDictionaryRouting(d_model, num_centroids, temperature=1e-3).to(device)
    layer_hot = SphericalDictionaryRouting(d_model, num_centroids, temperature=1e3).to(device)
    z_test = torch.randn(8, d_model, device=device)

    out_cold = layer_cold(z_test)
    out_hot = layer_hot(z_test)

    assert not torch.isnan(out_cold).any() and not torch.isinf(out_cold).any(), "Cold T produced NaNs/Infs"
    assert not torch.isnan(out_hot).any() and not torch.isinf(out_hot).any(), "Hot T produced NaNs/Infs"
    print("[PASS] Test 5: Extreme Bandwidth Regimes Handled Gracefully (T=1e-3, T=1e3)")

    # -------------------------------------------------------------------------
    # Test 6: Codebook Degeneracy (Zero & Collinear Centroids)
    # -------------------------------------------------------------------------
    layer_degen = SphericalDictionaryRouting(d_model, num_centroids).to(device)
    with torch.no_grad():
        # First centroid set to exact zero, remaining centroids identical to e_1
        layer_degen.centroids.copy_(torch.zeros_like(layer_degen.centroids))
        layer_degen.centroids[1:, 0] = 1.0

    z_degen = torch.randn(4, d_model, device=device, requires_grad=True)
    out_degen = layer_degen(z_degen)
    loss_degen = out_degen.sum()
    loss_degen.backward()

    assert not torch.isnan(out_degen).any(), "Degenerate codebook produced NaN output"
    assert not torch.isnan(z_degen.grad).any(), "Degenerate codebook produced NaN gradients"
    print("[PASS] Test 6: Codebook Degeneracy (Zero Centroid & Rank-1 Subspace) Stable")

    # -------------------------------------------------------------------------
    # Test 7: Dual Entropy Objectives & Cache Integrity
    # -------------------------------------------------------------------------
    # Config A: Batch only
    layer_a = SphericalDictionaryRouting(d_model, num_centroids, batch_entropy_weight=0.01, sample_entropy_weight=0.0).to(device)
    z_a = torch.randn(16, d_model, device=device, requires_grad=True)
    _, loss_a = layer_a(z_a, return_entropy_loss=True)
    assert layer_a.last_batch_entropy is not None and layer_a.last_sample_entropy is None
    loss_a.backward()
    assert layer_a.centroids.grad is not None and layer_a.centroids.grad.norm().item() > 0.0

    # Config B: Sample only
    layer_b = SphericalDictionaryRouting(d_model, num_centroids, batch_entropy_weight=0.0, sample_entropy_weight=0.01).to(device)
    z_b = torch.randn(16, d_model, device=device, requires_grad=True)
    _, loss_b = layer_b(z_b, return_entropy_loss=True)
    assert layer_b.last_batch_entropy is None and layer_b.last_sample_entropy is not None
    loss_b.backward()
    assert layer_b.centroids.grad is not None and layer_b.centroids.grad.norm().item() > 0.0

    print("[PASS] Test 7: Dual Entropy Objectives Propagate Gradients & Maintain Cache Integrity")

    # -------------------------------------------------------------------------
    # Test 8: AMP Output and Gradient Numerical Fidelity Against FP32
    # -------------------------------------------------------------------------
    if torch.cuda.is_available():
        dev_type = "cuda"
        dtype_half = torch.float16
        autocast_ctx = torch.amp.autocast(device_type=dev_type, dtype=dtype_half) if hasattr(torch, "amp") else torch.cuda.amp.autocast(dtype=dtype_half)

        torch.manual_seed(42)
        z_input = torch.randn(4, d_model, device=device)

        # Baseline in pure FP32
        z_fp32 = z_input.clone().requires_grad_(True)
        out_fp32 = layer(z_fp32, hard=False)
        (out_fp32 ** 2).sum().backward()
        grad_fp32 = z_fp32.grad.clone()

        # Under AMP FP16
        z_half = z_input.clone().to(dtype_half).requires_grad_(True)
        with autocast_ctx:
            out_half = layer(z_half, hard=False)
            loss_half = (out_half ** 2).sum()
        loss_half.backward()
        grad_half = z_half.grad.clone()

        # Verify output and gradient relative discrepancies remain within half-precision tolerance
        rel_out_err = (torch.norm(out_fp32 - out_half.float()) / torch.norm(out_fp32)).item()
        rel_grad_err = (torch.norm(grad_fp32 - grad_half.float()) / torch.norm(grad_fp32)).item()

        assert rel_out_err < 1e-3, f"AMP output deviation too high: {rel_out_err}"
        assert rel_grad_err < 1.5e-2, f"AMP gradient deviation too high: {rel_grad_err}"
        print(f"[PASS] Test 8: AMP Fidelity Matches FP32 (Output RelErr={rel_out_err:.2e}, Grad RelErr={rel_grad_err:.2e})")
    else:
        print("[SKIP] Test 8: CUDA not available for direct AMP fidelity check")

    print("=" * 70)
    print("ALL TESTS AND MATHEMATICAL VERIFICATIONS PASSED.")
    print("=" * 70 + "\n")


if __name__ == "__main__":
    run_all_unit_tests()