"""
Email Template Utilities

Helper functions for email template processing.
"""
import uuid
import copy
from typing import Optional


def add_component_ids(puck_data: Optional[dict]) -> dict:
    """
    Add unique IDs to each component in Puck data.

    Puck requires each component in the content array to have a unique 'id' field.
    This function generates UUIDs for any components missing IDs.

    Args:
        puck_data: The Puck data structure with 'content' and 'root' keys

    Returns:
        A deep copy of puck_data with IDs added to all components,
        or empty dict if puck_data is None/empty
    """
    if not puck_data:
        return {'content': [], 'root': {}}

    # Make a deep copy to avoid modifying the original
    data = copy.deepcopy(puck_data)

    content = data.get('content', [])
    for item in content:
        if 'id' not in item:
            # Generate a readable ID with component type prefix
            item['id'] = f"{item.get('type', 'component')}-{uuid.uuid4().hex[:8]}"

    return data
