import numpy as np
import torch


def get_normalized_adj(A: np.ndarray) -> np.ndarray:
    """
    Symmetric degree-normalised adjacency with added self-loops.
    """
    A = A + np.eye(A.shape[0], dtype=np.float32)           # self loops
    degree = A.sum(1)
    degree[degree <= 1e-5] = 1e-5                          # avoid /0
    inv_sqrt = np.power(degree, -0.5)
    A_hat = (inv_sqrt[:, None] * A) * inv_sqrt[None, :]
    return A_hat.astype(np.float32)

'''
def get_normalized_adj(A):
    """
    Returns the degree-normalized adjacency matrix.
    :param A: Adjacency matrix of shape (num_nodes, num_nodes).
    :return: Degree-normalized adjacency matrix of shape (num_nodes, num_nodes).
    """
    # Add self-connections (identity matrix)
    A = A + np.diag(np.ones(A.shape[0], dtype=np.float32))

    # Compute degree matrix
    D = np.array(np.sum(A, axis=1)).reshape((-1,))
    D[D <= 1e-5] = 1e-5  # Prevent division by zero or inf

    # Compute normalized adjacency matrix
    diag = np.reciprocal(np.sqrt(D))
    A_wave = np.multiply(np.multiply(diag.reshape((-1, 1)), A),
                         diag.reshape((1, -1)))
    return A_wave
'''

def generate_dataset(X, num_timesteps_input, num_timesteps_output):
    """
    Takes node features for the graph and divides them into multiple samples
    along the time-axis by sliding a window of size (num_timesteps_input +
    num_timesteps_output) across it in steps of 1.
    :param X: Node features of shape (num_nodes, num_features, num_timesteps).
    :param num_timesteps_input: Number of input time steps for each sample.
    :param num_timesteps_output: Number of output time steps for each sample.
    :return:
        - Node features divided into multiple samples. Shape is
          (num_samples, num_nodes, num_features, num_timesteps_input).
        - Node targets for the samples. Shape is
          (num_samples, num_nodes, num_timesteps_output).
    """
    # Generate start and end indices for sliding window
    indices = [
        (i, i + (num_timesteps_input + num_timesteps_output))
        for i in range(X.shape[2] - (num_timesteps_input + num_timesteps_output) + 1)
    ]

    # Save samples
    features, target = [], []
    for i, j in indices:
        # Input features: (num_nodes, num_features, num_timesteps_input)
        features.append(X[:, :, i: i + num_timesteps_input].transpose((0, 2, 1)))

        # Target: (num_nodes, num_timesteps_output)
        target.append(X[:, 0, i + num_timesteps_input: j])  # Assuming speed is the first feature

    # Convert to torch tensors
    return (
        torch.from_numpy(np.array(features)).float(),  # Shape: (num_samples, num_nodes, num_features, num_timesteps_input)
        torch.from_numpy(np.array(target)).float(),  # Shape: (num_samples, num_nodes, num_timesteps_output)
    )