from .client import NotifiedByClient


def subscribe_to_flow(flow_trigger, email, first_name=None, last_name=None,
                      flags=None, client=None):
    """
    Subscribe a recipient to an email flow.

    Automatically creates or updates the recipient record with the provided
    information. Flows are automated email sequences that send over time.

    Args:
        flow_trigger: Flow identifier/keyword (e.g., 'welcome_series', 'onboarding')
        email: Recipient email address
        first_name: Optional first name for personalization
        last_name: Optional last name for personalization
        flags: Optional list of flag strings for segmentation (e.g., ['premium', 'beta'])
        client: Optional NotifiedByClient instance (created if not provided)

    Returns:
        dict: API response with subscription details including:
            - flow_trigger: The flow keyword
            - email: Recipient email
            - Additional subscription metadata

    Raises:
        NotifiedByAPIError: If subscription fails
        NotifiedByConfigError: If API key not configured
        NotifiedByValidationError: If data is invalid (bad email, unknown flow, etc.)

    Example:
        >>> subscribe_to_flow(
        ...     'welcome_series',
        ...     'user@example.com',
        ...     first_name='John',
        ...     flags=['premium', 'early_adopter']
        ... )
        {'flow_trigger': 'welcome_series', 'email': 'user@example.com', ...}
    """
    if client is None:
        client = NotifiedByClient()

    payload = {
        'flow_trigger': flow_trigger,
        '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('/flows/subscribe/', json=payload)


def unsubscribe_from_flow(flow_trigger, email, client=None):
    """
    Unsubscribe a recipient from an email flow.

    Removes the recipient from the specified flow. They will no longer receive
    emails from this flow sequence.

    Args:
        flow_trigger: Flow identifier/keyword to unsubscribe from
        email: Recipient email address
        client: Optional NotifiedByClient instance (created if not provided)

    Returns:
        dict: Empty dict or success confirmation

    Raises:
        NotifiedByAPIError: If unsubscribe fails
        NotifiedByConfigError: If API key not configured
        NotifiedByValidationError: If data is invalid
        NotifiedByNotFoundError: If subscription doesn't exist

    Example:
        >>> unsubscribe_from_flow('newsletter_weekly', 'user@example.com')
        {}
    """
    if client is None:
        client = NotifiedByClient()

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

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


def list_flow_subscriptions(page=1, client=None):
    """
    List all flow subscriptions for your team.

    Returns paginated list of all active, completed, and cancelled flow subscriptions.

    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 subscriptions
            - next: URL to next page (or None)
            - previous: URL to previous page (or None)
            - results: List of subscription dicts with:
                - id: Subscription ID
                - flow_name: Human-readable flow name
                - flow_trigger: Flow keyword
                - recipient_email: Subscriber email
                - status: 'active', 'completed', or 'cancelled'
                - current_step_order: Current step in sequence
                - next_send_date: When next email will send
                - created_at: Subscription start date
                - updated_at: Last update date

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

    Example:
        >>> result = list_flow_subscriptions(page=1)
        >>> print(f"Found {result['count']} subscriptions")
        >>> for sub in result['results']:
        ...     print(f"{sub['recipient_email']} - {sub['flow_name']} ({sub['status']})")
    """
    if client is None:
        client = NotifiedByClient()

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


def delete_all_subscriptions(client=None):
    """
    Delete all flow subscriptions for your team.

    WARNING: This is a dangerous operation that removes ALL subscriptions.
    Use with extreme caution, typically only for testing or cleanup.

    Args:
        client: Optional NotifiedByClient instance (created if not provided)

    Returns:
        dict: Empty dict (204 No Content)

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

    Example:
        >>> # DANGER: This deletes ALL subscriptions!
        >>> delete_all_subscriptions()
        {}
    """
    if client is None:
        client = NotifiedByClient()

    return client.delete('/flows/subscriptions/')
