"""Paso de mensajes reproducible para Oryon Learn.

edge_index[0] contiene orígenes y edge_index[1] destinos. Cada columna es
una arista. Las operaciones conservan multiaristas y admiten nodos aislados.
"""
import numpy as np


def gather(x, index):
    return np.asarray(x)[np.asarray(index, dtype=np.int64)]


def gather_backward(grad, index, n):
    out = np.zeros((n, grad.shape[1]), dtype=grad.dtype)
    np.add.at(out, np.asarray(index, dtype=np.int64), grad)
    return out


def scatter_sum(messages, dst, n):
    out = np.zeros((n, messages.shape[1]), dtype=messages.dtype)
    np.add.at(out, np.asarray(dst, dtype=np.int64), messages)
    return out


def scatter_mean(messages, dst, n):
    counts = np.bincount(np.asarray(dst, dtype=np.int64), minlength=n)
    out = scatter_sum(messages, dst, n)
    return out / np.maximum(counts[:, None], 1), counts


def scatter_max(messages, dst, n):
    """Máximo por destino y canal; sin mensajes devuelve cero.

    En empates la VJP elegida reparte por igual entre todos los ganadores.
    """
    dst = np.asarray(dst, dtype=np.int64)
    out = np.full((n, messages.shape[1]), -np.inf, dtype=messages.dtype)
    np.maximum.at(out, dst, messages)
    counts = np.bincount(dst, minlength=n)
    out[counts == 0] = 0
    winners = messages == out[dst]
    ties = np.zeros_like(out, dtype=np.int64)
    np.add.at(ties, dst, winners.astype(np.int64))
    return out, (dst, winners, ties)


def scatter_max_backward(grad_out, argmax, num_edges):
    dst, winners, ties = argmax
    if len(dst) != num_edges:
        raise ValueError('num_edges no coincide con el registro de máximos')
    return grad_out[dst] * winners / np.maximum(ties[dst], 1)


def aggregate(messages, dst, n, mode='sum'):
    if mode == 'sum':
        return scatter_sum(messages, dst, n), (mode, np.asarray(dst, dtype=np.int64), None)
    if mode == 'mean':
        out, counts = scatter_mean(messages, dst, n)
        return out, (mode, np.asarray(dst, dtype=np.int64), counts)
    if mode == 'max':
        out, cache = scatter_max(messages, dst, n)
        return out, (mode, np.asarray(dst, dtype=np.int64), cache)
    raise ValueError('agregador desconocido')


def aggregate_backward(grad, cache):
    mode, dst, aux = cache
    if mode == 'sum':
        return grad[dst]
    if mode == 'mean':
        return grad[dst] / np.maximum(aux[dst, None], 1)
    return scatter_max_backward(grad, aux, len(dst))


def collate(graphs):
    """Concatena pares (x, edge_index), desplazando índices por grafo."""
    xs, es, batches = [], [], []
    offset = 0
    for graph_id, (x, edge_index) in enumerate(graphs):
        x = np.asarray(x)
        e = np.asarray(edge_index, dtype=np.int64)
        if e.ndim != 2 or e.shape[0] != 2:
            raise ValueError('edge_index debe tener forma (2, E)')
        if e.size and (e.min() < 0 or e.max() >= len(x)):
            raise ValueError('índice fuera del grafo local')
        xs.append(x); es.append(e + offset)
        batches.append(np.full(len(x), graph_id, dtype=np.int64))
        offset += len(x)
    if not xs:
        raise ValueError('el lote no puede estar vacío')
    return np.concatenate(xs), np.concatenate(es, axis=1), np.concatenate(batches)


def readout(x, batch, num_graphs, mode='sum'):
    return aggregate(np.asarray(x), np.asarray(batch), num_graphs, mode)[0]


class MPLayer:
    """Mensaje MLP y actualización residual; d de entrada y salida coinciden.

    forward puede devolver una caché explícita para diferenciar varias ramas
    (por ejemplo, entradas original y corrupta en DGI) antes de un paso SGD.
    """
    def __init__(self, d, hidden, edge_dim=0, aggregation='sum', seed=0):
        if aggregation not in ('sum', 'mean', 'max'):
            raise ValueError('agregador desconocido')
        self.d, self.hidden, self.edge_dim, self.aggregation = d, hidden, edge_dim, aggregation
        r = np.random.default_rng(seed)
        self.params = {
            'W1': r.normal(0, 1/np.sqrt(2*d+edge_dim), (2*d+edge_dim, hidden)),
            'b1': np.zeros(hidden),
            'W2': r.normal(0, 1/np.sqrt(hidden), (hidden, hidden)),
            'b2': np.zeros(hidden),
            'Wu': r.normal(0, 1/np.sqrt(hidden), (hidden, d)),
            'bu': np.zeros(d),
        }
        self.cache = None

    def forward(self, x, edge_index, edge_attr=None, return_cache=False):
        x = np.asarray(x, dtype=float)
        e = np.asarray(edge_index, dtype=np.int64)
        if x.ndim != 2 or x.shape[1] != self.d or e.ndim != 2 or e.shape[0] != 2:
            raise ValueError('formas incompatibles de x o edge_index')
        src, dst = e
        if e.size and (e.min() < 0 or e.max() >= len(x)):
            raise ValueError('índice de nodo fuera de rango')
        if edge_attr is None:
            edge_attr = np.zeros((e.shape[1], self.edge_dim), dtype=x.dtype)
        edge_attr = np.asarray(edge_attr, dtype=float)
        if edge_attr.shape != (e.shape[1], self.edge_dim):
            raise ValueError('forma incompatible de edge_attr')
        z = np.concatenate([gather(x, src), gather(x, dst), edge_attr], axis=1)
        p = self.params
        pre = z @ p['W1'] + p['b1']
        hidden = np.maximum(pre, 0)
        messages = hidden @ p['W2'] + p['b2']
        agg, agg_cache = aggregate(messages, dst, len(x), self.aggregation)
        out = x + agg @ p['Wu'] + p['bu']
        cache = (x, src, dst, z, pre, hidden, agg, agg_cache)
        self.cache = cache
        return (out, cache) if return_cache else out

    def backward(self, grad_out, cache=None):
        if cache is None:
            cache = self.cache
        if cache is None:
            raise ValueError('llama a forward antes de backward')
        x, src, dst, z, pre, hidden, agg, agg_cache = cache
        g = np.asarray(grad_out, dtype=float)
        if g.shape != x.shape:
            raise ValueError('gradiente de salida de forma incompatible')
        p = self.params
        grads = {'Wu': agg.T @ g, 'bu': g.sum(axis=0)}
        gmsg = aggregate_backward(g @ p['Wu'].T, agg_cache)
        grads['W2'] = hidden.T @ gmsg; grads['b2'] = gmsg.sum(axis=0)
        gpre = (gmsg @ p['W2'].T) * (pre > 0)
        grads['W1'] = z.T @ gpre; grads['b1'] = gpre.sum(axis=0)
        gz = gpre @ p['W1'].T
        grads['x'] = g + gather_backward(gz[:, :self.d], src, len(x)) + gather_backward(gz[:, self.d:2*self.d], dst, len(x))
        grads['edge_attr'] = gz[:, 2*self.d:]
        return grads

    def step(self, grads, lr):
        for name in self.params:
            self.params[name] -= lr * grads[name]


def torch_layer_from_numpy(layer):
    """Crea el equivalente PyTorch solo cuando el runtime local lo tiene."""
    import torch
    from torch import nn

    class TorchMPLayer(nn.Module):
        def __init__(self, source):
            super().__init__()
            self.d, self.edge_dim, self.aggregation = source.d, source.edge_dim, source.aggregation
            for name, value in source.params.items():
                self.register_parameter(name, nn.Parameter(torch.as_tensor(value.copy(), dtype=torch.float64)))

        def forward(self, x, edge_index, edge_attr=None):
            src, dst = edge_index
            if edge_attr is None:
                edge_attr = x.new_zeros((src.numel(), self.edge_dim))
            z = torch.cat((x[src], x[dst], edge_attr), dim=1)
            msg = torch.relu(z @ self.W1 + self.b1) @ self.W2 + self.b2
            n = x.shape[0]
            if self.aggregation == 'max':
                index = dst[:, None].expand_as(msg)
                initial = x.new_full((n, msg.shape[1]), -torch.inf)
                agg = initial.scatter_reduce(0, index, msg, reduce='amax', include_self=False)
                counts = torch.bincount(dst, minlength=n)
                agg = torch.where(counts[:, None] > 0, agg, torch.zeros_like(agg))
            else:
                agg = x.new_zeros((n, msg.shape[1])).index_add(0, dst, msg)
                if self.aggregation == 'mean':
                    counts = torch.bincount(dst, minlength=n).clamp_min(1)
                    agg = agg / counts[:, None]
            return x + agg @ self.Wu + self.bu

    return TorchMPLayer(layer)
