import torch
from torch_geometric.datasets import TUDataset
from torch_geometric.utils import degree

def load_and_preprocess_tu_dataset(name='MUTAG', norm='log', eps=1e-5):
    """
    Load and preprocess a TU dataset by adding normalized node degree
    as node features.

    Args:
        name (str): Name of the dataset (default: 'MUTAG').
        norm (str): Normalization method for node degree ('log' or 'minmax').
        eps (float): A small constant to prevent division by zero.

    Returns:
        List[torch_geometric.data.Data]: Preprocessed graph data list.
    """
    raw_dataset = TUDataset(root='../data', name=name)

    def _add_degree_feature(data):
        num_nodes = data.num_nodes
        deg = degree(data.edge_index[0], num_nodes=num_nodes)

        if norm == 'log':
            deg = torch.log1p(deg) / (torch.log1p(deg.max().clone().detach()) + eps)
        elif norm == 'minmax':
            deg = (deg - deg.min()) / (deg.max() - deg.min() + eps)

        deg = deg.view(-1, 1)

        # If original node features exist, concatenate the degree feature
        if hasattr(data, 'x') and data.x is not None:
            data.x = torch.cat([data.x, deg], dim=1)
        else:
            data.x = deg

        return data

    dataset = [_add_degree_feature(data) for data in raw_dataset]
    return dataset
