import torch
import torch.nn.functional as F


def pad_and_batch_tensors(tensor_list, max_size):
    """
    Pads a list of tensors along the first dimension and batches them into a single tensor.

    Parameters:
    - tensor_list: List[Tensor], the list of tensors to pad and concatenate.
    - max_size: int, the desired size of the first dimension after padding.

    Returns:
    - batched_tensor: Tensor, the padded and concatenated tensor.
    - mask: BoolTensor, a boolean mask where padded values are marked as False.
    """
    padded_tensors = []
    mask = torch.zeros(
        (len(tensor_list), max_size),
        dtype=tensor_list[0].dtype,
        device=tensor_list[0].device,
    )

    for i, tensor in enumerate(tensor_list):
        current_size = tensor.shape[0]
        if current_size > max_size:
            raise ValueError(
                f"Tensor at index {i} has size {current_size} along the first dimension, "
                f"which exceeds the maximum allowed size of {max_size}."
            )

        pad_size = max_size - current_size
        padding = (0, 0) * (tensor.dim() - 1) + (0, pad_size)
        padded_tensor = F.pad(tensor, padding)
        padded_tensors.append(padded_tensor)
        mask[i, :current_size] = 1.0

    batched_tensor = torch.stack(padded_tensors)
    return batched_tensor, mask
