"""Validation utilities for recipient data."""

from typing import Any

from pydantic import ValidationError

from .types import RecipientData


def validate_recipient_data(data: dict[str, Any]) -> RecipientData:
    """Validate recipient data dictionary.

    Parses and validates a dictionary against the RecipientData model.

    Args:
        data: Dictionary to validate

    Returns:
        Validated RecipientData object

    Raises:
        ValidationError: If validation fails

    Example:
        ```python
        try:
            validated = validate_recipient_data({
                "channel_id": "ch_test",
                "tenant_id": "123e4567-e89b-12d3-a456-426614174000",
                "timestamp": "2025-12-15T12:00:00Z",
                "data": {"value": 1},
                "metadata": {"ingress_timestamp": "2025-12-15T12:00:01Z"},
            })
            # Use validated data...
        except ValidationError as e:
            print(f"Validation failed: {e}")
        ```
    """
    return RecipientData.model_validate(data)


def safe_validate_recipient_data(
    data: dict[str, Any],
) -> tuple[RecipientData | None, list[dict[str, Any]] | None]:
    """Safely validate recipient data without raising exceptions.

    Returns a tuple of (validated_data, errors). Exactly one will be None.

    Args:
        data: Dictionary to validate

    Returns:
        Tuple of (validated_data, errors):
        - If validation succeeds: (RecipientData, None)
        - If validation fails: (None, list of error dictionaries)

    Example:
        ```python
        validated, errors = safe_validate_recipient_data(data)

        if validated:
            # Use validated data
            print(f"Channel: {validated.channel_id}")
        else:
            # Handle errors
            for error in errors:
                print(f"Error at {error['loc']}: {error['msg']}")
        ```
    """
    try:
        validated = RecipientData.model_validate(data)
        return validated, None
    except ValidationError as e:
        errors = [
            {
                "loc": list(error["loc"]),
                "msg": error["msg"],
                "type": error["type"],
            }
            for error in e.errors()
        ]
        return None, errors
