from .client import NotifiedByClient


def create_or_update_recipient(email, first_name=None, last_name=None,
                                flags=None, client=None):
    """
    Create or update a recipient with metadata.

    If a recipient with this email already exists, their information will be
    updated. Otherwise, a new recipient is created.

    Args:
        email: Recipient email address (required, unique identifier)
        first_name: Optional first name for personalization
        last_name: Optional last name for personalization
        flags: Optional list of flag strings for segmentation/tagging
        client: Optional NotifiedByClient instance (created if not provided)

    Returns:
        dict: Recipient data including:
            - sqid: Unique recipient ID
            - email: Recipient email
            - first_name: First name (if provided)
            - last_name: Last name (if provided)
            - has_been_sent_email: Whether recipient has received any emails
            - created_at: When recipient was first created
            - updated_at: When recipient was last updated

    Raises:
        NotifiedByAPIError: If request fails
        NotifiedByConfigError: If API key not configured
        NotifiedByValidationError: If email is invalid

    Example:
        >>> recipient = create_or_update_recipient(
        ...     'user@example.com',
        ...     first_name='Jane',
        ...     last_name='Doe',
        ...     flags=['premium', 'beta_tester']
        ... )
        >>> print(recipient['sqid'])
        'abc123xyz'
    """
    if client is None:
        client = NotifiedByClient()

    payload = {'email': email}

    if first_name:
        payload['first_name'] = first_name
    if last_name:
        payload['last_name'] = last_name
    if flags:
        payload['flags'] = flags

    return client.post('/recipients/', json=payload)


def list_recipients(page=1, client=None):
    """
    List all recipients for your team.

    Returns paginated list of all recipients who have been created or have
    received emails through NotifiedBy.

    Args:
        page: Page number for pagination (default: 1)
        client: Optional NotifiedByClient instance (created if not provided)

    Returns:
        dict: Paginated response with:
            - count: Total number of recipients
            - next: URL to next page (or None)
            - previous: URL to previous page (or None)
            - results: List of recipient dicts with:
                - sqid: Unique recipient ID
                - email: Recipient email
                - first_name: First name (if set)
                - last_name: Last name (if set)
                - has_been_sent_email: Whether they've received emails
                - created_at: When recipient was created
                - updated_at: Last update time

    Raises:
        NotifiedByAPIError: If request fails
        NotifiedByConfigError: If API key not configured

    Example:
        >>> result = list_recipients(page=1)
        >>> print(f"Total recipients: {result['count']}")
        >>> for recipient in result['results']:
        ...     print(f"{recipient['email']} - {recipient['first_name']}")
    """
    if client is None:
        client = NotifiedByClient()

    params = {'page': page}
    return client.get('/recipients/', params=params)


def set_recipient_flags(email, flags, client=None):
    """
    Set flags on a recipient for segmentation and targeting.

    Flags are custom tags you can use to segment recipients (e.g., 'premium',
    'churned', 'early_adopter'). These can be used to trigger different flows
    or filter recipients.

    Args:
        email: Recipient email address
        flags: List of flag strings to set (e.g., ['premium', 'paid'])
        client: Optional NotifiedByClient instance (created if not provided)

    Returns:
        dict: Empty dict or success confirmation

    Raises:
        NotifiedByAPIError: If request fails
        NotifiedByConfigError: If API key not configured
        NotifiedByValidationError: If email is invalid
        NotifiedByNotFoundError: If recipient doesn't exist

    Example:
        >>> set_recipient_flags('user@example.com', ['premium', 'annual_plan'])
        {}
    """
    if client is None:
        client = NotifiedByClient()

    payload = {
        'email': email,
        'flags': flags,
    }

    return client.post('/recipients/flags/set/', json=payload)


def clear_recipient_flags(email, flags, client=None):
    """
    Remove specific flags from a recipient.

    Clears the specified flags from the recipient. Other flags remain unchanged.

    Args:
        email: Recipient email address
        flags: List of flag strings to remove (e.g., ['trial', 'pending'])
        client: Optional NotifiedByClient instance (created if not provided)

    Returns:
        dict: Empty dict or success confirmation

    Raises:
        NotifiedByAPIError: If request fails
        NotifiedByConfigError: If API key not configured
        NotifiedByValidationError: If email is invalid
        NotifiedByNotFoundError: If recipient doesn't exist

    Example:
        >>> # User cancelled subscription, remove premium flag
        >>> clear_recipient_flags('user@example.com', ['premium', 'paid'])
        {}
    """
    if client is None:
        client = NotifiedByClient()

    payload = {
        'email': email,
        'flags': flags,
    }

    return client.post('/recipients/flags/clear/', json=payload)
