"""Diffusion Policy compacta con U-Net temporal, FiLM y DDIM determinista."""
import copy
import math
import torch
from torch import nn
import torch.nn.functional as F


def time_embedding(t, dim):
    half = dim // 2
    frequencies = torch.exp(-math.log(10000.0) * torch.arange(half, device=t.device) / max(half - 1, 1))
    angles = t.float()[:, None] * frequencies[None]
    result = torch.cat((angles.sin(), angles.cos()), dim=-1)
    return F.pad(result, (0, dim - result.shape[-1]))


class FiLMBlock(nn.Module):
    def __init__(self, channels, cond_dim):
        super().__init__()
        self.conv1 = nn.Conv1d(channels, channels, 3, padding=1)
        self.conv2 = nn.Conv1d(channels, channels, 3, padding=1)
        self.norm1 = nn.GroupNorm(8, channels)
        self.norm2 = nn.GroupNorm(8, channels)
        self.film = nn.Linear(cond_dim, 2 * channels)

    def forward(self, x, cond):
        scale, bias = self.film(cond).chunk(2, dim=-1)
        h = self.norm1(self.conv1(x))
        h = F.silu(h * (1 + scale[..., None]) + bias[..., None])
        return x + self.conv2(F.silu(self.norm2(h)))


class DiffusionPolicy(nn.Module):
    def __init__(self, state_dim=2, action_dim=2, width=64, time_dim=64):
        super().__init__()
        self.time_dim = time_dim
        self.vision = nn.Sequential(nn.Conv2d(3, 32, 5, 2, 2), nn.SiLU(),
                                    nn.Conv2d(32, 64, 3, 2, 1), nn.SiLU(),
                                    nn.Conv2d(64, 64, 3, 2, 1), nn.SiLU(),
                                    nn.AdaptiveAvgPool2d(1), nn.Flatten())
        self.cond = nn.Sequential(nn.Linear(64 + state_dim + time_dim, width * 2), nn.SiLU(), nn.Linear(width * 2, width * 2))
        self.input = nn.Conv1d(action_dim, width, 1)
        self.down_block = FiLMBlock(width, width * 2)
        self.down = nn.Conv1d(width, width, 3, stride=2, padding=1)
        self.middle = FiLMBlock(width, width * 2)
        self.up = nn.ConvTranspose1d(width, width, 4, stride=2, padding=1)
        self.up_block = FiLMBlock(width, width * 2)
        self.output = nn.Conv1d(width, action_dim, 1)

    def forward(self, noisy, timestep, image, state):
        if noisy.shape[1] % 2:
            raise ValueError('El horizonte debe ser par')
        cond = self.cond(torch.cat((self.vision(image), state, time_embedding(timestep, self.time_dim)), dim=-1))
        x = self.input(noisy.transpose(1, 2))
        skip = self.down_block(x, cond)
        x = self.middle(self.down(skip), cond)
        x = self.up(x) + skip
        return self.output(self.up_block(x, cond)).transpose(1, 2)


def cosine_alphas(steps=100, s=0.008):
    """Productos acumulados de alfa, con beta limitado a 0.999."""
    x = torch.linspace(0, steps, steps + 1, dtype=torch.float64) / steps
    f = torch.cos((x + s) / (1 + s) * math.pi / 2).square()
    f = f / f[0]
    beta = (1 - f[1:] / f[:-1]).clamp(0, 0.999)
    return torch.cumprod(1 - beta, dim=0).float()


def noise_loss(model, actions, image, state, alphas, generator=None):
    b = actions.shape[0]
    t = torch.randint(len(alphas), (b,), device=actions.device, generator=generator)
    noise = torch.randn(actions.shape, device=actions.device, dtype=actions.dtype, generator=generator)
    a = alphas[t, None, None]
    noisy = a.sqrt() * actions + (1 - a).sqrt() * noise
    return F.mse_loss(model(noisy, t, image, state), noise)


@torch.no_grad()
def ddim(model, image, state, alphas, horizon, action_dim, steps=10, generator=None, return_trace=False):
    """DDIM eta=0: determinista condicionado al ruido inicial."""
    if not 1 <= steps <= len(alphas):
        raise ValueError('Número inválido de pasos DDIM')
    x = torch.randn((len(state), horizon, action_dim), device=state.device, generator=generator)
    trace = [x.detach().clone()] if return_trace else None
    schedule = torch.linspace(len(alphas) - 1, 0, steps, device=state.device).round().long()
    for i, t in enumerate(schedule):
        a = alphas[t]
        eps = model(x, t.expand(len(state)), image, state)
        clean = (x - (1 - a).sqrt() * eps) / a.sqrt()
        previous = alphas[schedule[i + 1]] if i + 1 < len(schedule) else torch.ones_like(a)
        x = previous.sqrt() * clean + (1 - previous).sqrt() * eps
        if trace is not None: trace.append(x.detach().clone())
    return (x, torch.stack(trace)) if trace is not None else x


class EMA:
    def __init__(self, model, decay=0.995):
        self.model = copy.deepcopy(model).eval()
        self.decay = decay
        for p in self.model.parameters(): p.requires_grad_(False)

    @torch.no_grad()
    def update(self, model):
        for dst, src in zip(self.model.parameters(), model.parameters()):
            dst.lerp_(src, 1 - self.decay)
